From 1367261e7198447a80920eea72ef7a18cf14d375 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 26 Nov 2024 17:13:57 +0000 Subject: [PATCH 1/2] docs: A comment for enum `CryptoKeyVersionAlgorithm` is changed PiperOrigin-RevId: 700331075 Source-Link: https://github.com/googleapis/googleapis/commit/3b7310bebab65971237b68c6320fa55ebf192fb8 Source-Link: https://github.com/googleapis/googleapis-gen/commit/9eda366d22f320ed4d4d5ca9f1d58bbe6efb8805 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWttcy8uT3dsQm90LnlhbWwiLCJoIjoiOWVkYTM2NmQyMmYzMjBlZDRkNGQ1Y2E5ZjFkNThiYmU2ZWZiODgwNSJ9 --- .../google-cloud-kms/v1/.coveragerc | 13 + owl-bot-staging/google-cloud-kms/v1/.flake8 | 33 + .../google-cloud-kms/v1/MANIFEST.in | 2 + .../google-cloud-kms/v1/README.rst | 49 + .../v1/docs/_static/custom.css | 3 + .../google-cloud-kms/v1/docs/conf.py | 376 + .../google-cloud-kms/v1/docs/index.rst | 7 + .../v1/docs/kms_v1/autokey.rst | 10 + .../v1/docs/kms_v1/autokey_admin.rst | 6 + .../v1/docs/kms_v1/ekm_service.rst | 10 + .../v1/docs/kms_v1/key_management_service.rst | 10 + .../v1/docs/kms_v1/services_.rst | 9 + .../v1/docs/kms_v1/types_.rst | 6 + .../v1/google/cloud/kms/__init__.py | 193 + .../v1/google/cloud/kms/gapic_version.py | 16 + .../v1/google/cloud/kms/py.typed | 2 + .../v1/google/cloud/kms_v1/__init__.py | 194 + .../google/cloud/kms_v1/gapic_metadata.json | 700 + .../v1/google/cloud/kms_v1/gapic_version.py | 16 + .../v1/google/cloud/kms_v1/py.typed | 2 + .../google/cloud/kms_v1/services/__init__.py | 15 + .../cloud/kms_v1/services/autokey/__init__.py | 22 + .../kms_v1/services/autokey/async_client.py | 1074 + .../cloud/kms_v1/services/autokey/client.py | 1423 + .../cloud/kms_v1/services/autokey/pagers.py | 162 + .../services/autokey/transports/README.rst | 9 + .../services/autokey/transports/__init__.py | 38 + .../services/autokey/transports/base.py | 298 + .../services/autokey/transports/grpc.py | 502 + .../autokey/transports/grpc_asyncio.py | 584 + .../services/autokey/transports/rest.py | 1119 + .../services/autokey/transports/rest_base.py | 434 + .../kms_v1/services/autokey_admin/__init__.py | 22 + .../services/autokey_admin/async_client.py | 1018 + .../kms_v1/services/autokey_admin/client.py | 1358 + .../autokey_admin/transports/README.rst | 9 + .../autokey_admin/transports/__init__.py | 38 + .../services/autokey_admin/transports/base.py | 302 + .../services/autokey_admin/transports/grpc.py | 477 + .../autokey_admin/transports/grpc_asyncio.py | 569 + .../services/autokey_admin/transports/rest.py | 1077 + .../autokey_admin/transports/rest_base.py | 434 + .../kms_v1/services/ekm_service/__init__.py | 22 + .../services/ekm_service/async_client.py | 1526 + .../kms_v1/services/ekm_service/client.py | 1880 ++ .../kms_v1/services/ekm_service/pagers.py | 162 + .../ekm_service/transports/README.rst | 9 + .../ekm_service/transports/__init__.py | 38 + .../services/ekm_service/transports/base.py | 368 + .../services/ekm_service/transports/grpc.py | 579 + .../ekm_service/transports/grpc_asyncio.py | 701 + .../services/ekm_service/transports/rest.py | 1553 ++ .../ekm_service/transports/rest_base.py | 602 + .../key_management_service/__init__.py | 22 + .../key_management_service/async_client.py | 4163 +++ .../services/key_management_service/client.py | 4517 +++ .../services/key_management_service/pagers.py | 568 + .../transports/README.rst | 9 + .../transports/__init__.py | 38 + .../key_management_service/transports/base.py | 863 + .../key_management_service/transports/grpc.py | 1250 + .../transports/grpc_asyncio.py | 1677 ++ .../key_management_service/transports/rest.py | 4008 +++ .../transports/rest_base.py | 1532 ++ .../v1/google/cloud/kms_v1/types/__init__.py | 182 + .../v1/google/cloud/kms_v1/types/autokey.py | 214 + .../cloud/kms_v1/types/autokey_admin.py | 178 + .../google/cloud/kms_v1/types/ekm_service.py | 554 + .../v1/google/cloud/kms_v1/types/resources.py | 1383 + .../v1/google/cloud/kms_v1/types/service.py | 2528 ++ owl-bot-staging/google-cloud-kms/v1/mypy.ini | 3 + .../google-cloud-kms/v1/noxfile.py | 280 + ..._autokey_admin_get_autokey_config_async.py | 52 + ...d_autokey_admin_get_autokey_config_sync.py | 52 + ...min_show_effective_autokey_config_async.py | 52 + ...dmin_show_effective_autokey_config_sync.py | 52 + ...tokey_admin_update_autokey_config_async.py | 51 + ...utokey_admin_update_autokey_config_sync.py | 51 + ...nerated_autokey_create_key_handle_async.py | 60 + ...enerated_autokey_create_key_handle_sync.py | 60 + ..._generated_autokey_get_key_handle_async.py | 52 + ...1_generated_autokey_get_key_handle_sync.py | 52 + ...enerated_autokey_list_key_handles_async.py | 53 + ...generated_autokey_list_key_handles_sync.py | 53 + ...ekm_service_create_ekm_connection_async.py | 53 + ..._ekm_service_create_ekm_connection_sync.py | 53 + ...erated_ekm_service_get_ekm_config_async.py | 52 + ...nerated_ekm_service_get_ekm_config_sync.py | 52 + ...ed_ekm_service_get_ekm_connection_async.py | 52 + ...ted_ekm_service_get_ekm_connection_sync.py | 52 + ..._ekm_service_list_ekm_connections_async.py | 53 + ...d_ekm_service_list_ekm_connections_sync.py | 53 + ...ted_ekm_service_update_ekm_config_async.py | 51 + ...ated_ekm_service_update_ekm_config_sync.py | 51 + ...ekm_service_update_ekm_connection_async.py | 51 + ..._ekm_service_update_ekm_connection_sync.py | 51 + ...d_ekm_service_verify_connectivity_async.py | 52 + ...ed_ekm_service_verify_connectivity_sync.py | 52 + ...gement_service_asymmetric_decrypt_async.py | 53 + ...agement_service_asymmetric_decrypt_sync.py | 53 + ...anagement_service_asymmetric_sign_async.py | 52 + ...management_service_asymmetric_sign_sync.py | 52 + ...agement_service_create_crypto_key_async.py | 53 + ...nagement_service_create_crypto_key_sync.py | 53 + ...service_create_crypto_key_version_async.py | 52 + ..._service_create_crypto_key_version_sync.py | 52 + ...agement_service_create_import_job_async.py | 58 + ...nagement_service_create_import_job_sync.py | 58 + ...anagement_service_create_key_ring_async.py | 53 + ...management_service_create_key_ring_sync.py | 53 + ...ed_key_management_service_decrypt_async.py | 53 + ...ted_key_management_service_decrypt_sync.py | 53 + ...ervice_destroy_crypto_key_version_async.py | 52 + ...service_destroy_crypto_key_version_sync.py | 52 + ...ed_key_management_service_encrypt_async.py | 53 + ...ted_key_management_service_encrypt_sync.py | 53 + ...ent_service_generate_random_bytes_async.py | 51 + ...ment_service_generate_random_bytes_sync.py | 51 + ...management_service_get_crypto_key_async.py | 52 + ..._management_service_get_crypto_key_sync.py | 52 + ...nt_service_get_crypto_key_version_async.py | 52 + ...ent_service_get_crypto_key_version_sync.py | 52 + ...management_service_get_import_job_async.py | 52 + ..._management_service_get_import_job_sync.py | 52 + ...y_management_service_get_key_ring_async.py | 52 + ...ey_management_service_get_key_ring_sync.py | 52 + ...management_service_get_public_key_async.py | 52 + ..._management_service_get_public_key_sync.py | 52 + ...service_import_crypto_key_version_async.py | 55 + ..._service_import_crypto_key_version_sync.py | 55 + ..._service_list_crypto_key_versions_async.py | 53 + ...t_service_list_crypto_key_versions_sync.py | 53 + ...nagement_service_list_crypto_keys_async.py | 53 + ...anagement_service_list_crypto_keys_sync.py | 53 + ...nagement_service_list_import_jobs_async.py | 53 + ...anagement_service_list_import_jobs_sync.py | 53 + ...management_service_list_key_rings_async.py | 53 + ..._management_service_list_key_rings_sync.py | 53 + ...d_key_management_service_mac_sign_async.py | 53 + ...ed_key_management_service_mac_sign_sync.py | 53 + ...key_management_service_mac_verify_async.py | 54 + ..._key_management_service_mac_verify_sync.py | 54 + ...ey_management_service_raw_decrypt_async.py | 54 + ...key_management_service_raw_decrypt_sync.py | 54 + ...ey_management_service_raw_encrypt_async.py | 53 + ...key_management_service_raw_encrypt_sync.py | 53 + ...ervice_restore_crypto_key_version_async.py | 52 + ...service_restore_crypto_key_version_sync.py | 52 + ...agement_service_update_crypto_key_async.py | 51 + ...update_crypto_key_primary_version_async.py | 53 + ..._update_crypto_key_primary_version_sync.py | 53 + ...nagement_service_update_crypto_key_sync.py | 51 + ...service_update_crypto_key_version_async.py | 51 + ..._service_update_crypto_key_version_sync.py | 51 + .../snippet_metadata_google.cloud.kms.v1.json | 6800 +++++ .../v1/scripts/fixup_kms_v1_keywords.py | 219 + owl-bot-staging/google-cloud-kms/v1/setup.py | 99 + .../v1/testing/constraints-3.10.txt | 7 + .../v1/testing/constraints-3.11.txt | 7 + .../v1/testing/constraints-3.12.txt | 7 + .../v1/testing/constraints-3.13.txt | 7 + .../v1/testing/constraints-3.7.txt | 11 + .../v1/testing/constraints-3.8.txt | 7 + .../v1/testing/constraints-3.9.txt | 7 + .../google-cloud-kms/v1/tests/__init__.py | 16 + .../v1/tests/unit/__init__.py | 16 + .../v1/tests/unit/gapic/__init__.py | 16 + .../v1/tests/unit/gapic/kms_v1/__init__.py | 16 + .../tests/unit/gapic/kms_v1/test_autokey.py | 5012 ++++ .../unit/gapic/kms_v1/test_autokey_admin.py | 4652 ++++ .../unit/gapic/kms_v1/test_ekm_service.py | 7787 ++++++ .../kms_v1/test_key_management_service.py | 22906 ++++++++++++++++ 172 files changed, 95966 insertions(+) create mode 100644 owl-bot-staging/google-cloud-kms/v1/.coveragerc create mode 100644 owl-bot-staging/google-cloud-kms/v1/.flake8 create mode 100644 owl-bot-staging/google-cloud-kms/v1/MANIFEST.in create mode 100644 owl-bot-staging/google-cloud-kms/v1/README.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/_static/custom.css create mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/conf.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/index.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey_admin.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/ekm_service.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/key_management_service.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/services_.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/types_.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/py.typed create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_metadata.json create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_version.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/py.typed create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/async_client.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/client.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/pagers.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/base.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/async_client.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/client.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/base.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/client.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/async_client.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/client.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/pagers.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/README.rst create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey_admin.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/ekm_service.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/resources.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/service.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/mypy.ini create mode 100644 owl-bot-staging/google-cloud-kms/v1/noxfile.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json create mode 100644 owl-bot-staging/google-cloud-kms/v1/scripts/fixup_kms_v1_keywords.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/setup.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.10.txt create mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.11.txt create mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.12.txt create mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.13.txt create mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.7.txt create mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.8.txt create mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.9.txt create mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/__init__.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey_admin.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_ekm_service.py create mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_key_management_service.py diff --git a/owl-bot-staging/google-cloud-kms/v1/.coveragerc b/owl-bot-staging/google-cloud-kms/v1/.coveragerc new file mode 100644 index 000000000000..ada4b5e633e6 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/cloud/kms/__init__.py + google/cloud/kms/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-kms/v1/.flake8 b/owl-bot-staging/google-cloud-kms/v1/.flake8 new file mode 100644 index 000000000000..29227d4cf419 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/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-kms/v1/MANIFEST.in b/owl-bot-staging/google-cloud-kms/v1/MANIFEST.in new file mode 100644 index 000000000000..97846726fb83 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/MANIFEST.in @@ -0,0 +1,2 @@ +recursive-include google/cloud/kms *.py +recursive-include google/cloud/kms_v1 *.py diff --git a/owl-bot-staging/google-cloud-kms/v1/README.rst b/owl-bot-staging/google-cloud-kms/v1/README.rst new file mode 100644 index 000000000000..9574e81c7eb6 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/README.rst @@ -0,0 +1,49 @@ +Python Client for Google Cloud Kms 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 Kms 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-kms/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-kms/v1/docs/_static/custom.css new file mode 100644 index 000000000000..06423be0b592 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/docs/_static/custom.css @@ -0,0 +1,3 @@ +dl.field-list > dt { + min-width: 100px +} diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/conf.py b/owl-bot-staging/google-cloud-kms/v1/docs/conf.py new file mode 100644 index 000000000000..7c9dfa8fbd1b --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/docs/conf.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# google-cloud-kms 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-kms" +copyright = u"2023, Google, LLC" +author = u"Google APIs" # TODO: autogenerate this bit + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'en' + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ["_build"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for Python", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-cloud-kms-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-kms.tex", + u"google-cloud-kms 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-kms", + u"Google Cloud Kms 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-kms", + u"google-cloud-kms Documentation", + author, + "google-cloud-kms", + "GAPIC library for Google Cloud Kms 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-kms/v1/docs/index.rst b/owl-bot-staging/google-cloud-kms/v1/docs/index.rst new file mode 100644 index 000000000000..8d79aeb30d1d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/docs/index.rst @@ -0,0 +1,7 @@ +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + kms_v1/services_ + kms_v1/types_ diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey.rst new file mode 100644 index 000000000000..266646a17c28 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey.rst @@ -0,0 +1,10 @@ +Autokey +------------------------- + +.. automodule:: google.cloud.kms_v1.services.autokey + :members: + :inherited-members: + +.. automodule:: google.cloud.kms_v1.services.autokey.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey_admin.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey_admin.rst new file mode 100644 index 000000000000..ae47377233b2 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey_admin.rst @@ -0,0 +1,6 @@ +AutokeyAdmin +------------------------------ + +.. automodule:: google.cloud.kms_v1.services.autokey_admin + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/ekm_service.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/ekm_service.rst new file mode 100644 index 000000000000..82f6e2a430b8 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/ekm_service.rst @@ -0,0 +1,10 @@ +EkmService +---------------------------- + +.. automodule:: google.cloud.kms_v1.services.ekm_service + :members: + :inherited-members: + +.. automodule:: google.cloud.kms_v1.services.ekm_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/key_management_service.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/key_management_service.rst new file mode 100644 index 000000000000..b34ce0281bb2 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/key_management_service.rst @@ -0,0 +1,10 @@ +KeyManagementService +-------------------------------------- + +.. automodule:: google.cloud.kms_v1.services.key_management_service + :members: + :inherited-members: + +.. automodule:: google.cloud.kms_v1.services.key_management_service.pagers + :members: + :inherited-members: diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/services_.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/services_.rst new file mode 100644 index 000000000000..18fe1076d51a --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/services_.rst @@ -0,0 +1,9 @@ +Services for Google Cloud Kms v1 API +==================================== +.. toctree:: + :maxdepth: 2 + + autokey + autokey_admin + ekm_service + key_management_service diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/types_.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/types_.rst new file mode 100644 index 000000000000..c78ef915f3a0 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Kms v1 API +================================= + +.. automodule:: google.cloud.kms_v1.types + :members: + :show-inheritance: diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/__init__.py new file mode 100644 index 000000000000..745e815f595c --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/__init__.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.kms import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.cloud.kms_v1.services.autokey.client import AutokeyClient +from google.cloud.kms_v1.services.autokey.async_client import AutokeyAsyncClient +from google.cloud.kms_v1.services.autokey_admin.client import AutokeyAdminClient +from google.cloud.kms_v1.services.autokey_admin.async_client import AutokeyAdminAsyncClient +from google.cloud.kms_v1.services.ekm_service.client import EkmServiceClient +from google.cloud.kms_v1.services.ekm_service.async_client import EkmServiceAsyncClient +from google.cloud.kms_v1.services.key_management_service.client import KeyManagementServiceClient +from google.cloud.kms_v1.services.key_management_service.async_client import KeyManagementServiceAsyncClient + +from google.cloud.kms_v1.types.autokey import CreateKeyHandleMetadata +from google.cloud.kms_v1.types.autokey import CreateKeyHandleRequest +from google.cloud.kms_v1.types.autokey import GetKeyHandleRequest +from google.cloud.kms_v1.types.autokey import KeyHandle +from google.cloud.kms_v1.types.autokey import ListKeyHandlesRequest +from google.cloud.kms_v1.types.autokey import ListKeyHandlesResponse +from google.cloud.kms_v1.types.autokey_admin import AutokeyConfig +from google.cloud.kms_v1.types.autokey_admin import GetAutokeyConfigRequest +from google.cloud.kms_v1.types.autokey_admin import ShowEffectiveAutokeyConfigRequest +from google.cloud.kms_v1.types.autokey_admin import ShowEffectiveAutokeyConfigResponse +from google.cloud.kms_v1.types.autokey_admin import UpdateAutokeyConfigRequest +from google.cloud.kms_v1.types.ekm_service import Certificate +from google.cloud.kms_v1.types.ekm_service import CreateEkmConnectionRequest +from google.cloud.kms_v1.types.ekm_service import EkmConfig +from google.cloud.kms_v1.types.ekm_service import EkmConnection +from google.cloud.kms_v1.types.ekm_service import GetEkmConfigRequest +from google.cloud.kms_v1.types.ekm_service import GetEkmConnectionRequest +from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsRequest +from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsResponse +from google.cloud.kms_v1.types.ekm_service import UpdateEkmConfigRequest +from google.cloud.kms_v1.types.ekm_service import UpdateEkmConnectionRequest +from google.cloud.kms_v1.types.ekm_service import VerifyConnectivityRequest +from google.cloud.kms_v1.types.ekm_service import VerifyConnectivityResponse +from google.cloud.kms_v1.types.resources import CryptoKey +from google.cloud.kms_v1.types.resources import CryptoKeyVersion +from google.cloud.kms_v1.types.resources import CryptoKeyVersionTemplate +from google.cloud.kms_v1.types.resources import ExternalProtectionLevelOptions +from google.cloud.kms_v1.types.resources import ImportJob +from google.cloud.kms_v1.types.resources import KeyAccessJustificationsPolicy +from google.cloud.kms_v1.types.resources import KeyOperationAttestation +from google.cloud.kms_v1.types.resources import KeyRing +from google.cloud.kms_v1.types.resources import PublicKey +from google.cloud.kms_v1.types.resources import AccessReason +from google.cloud.kms_v1.types.resources import ProtectionLevel +from google.cloud.kms_v1.types.service import AsymmetricDecryptRequest +from google.cloud.kms_v1.types.service import AsymmetricDecryptResponse +from google.cloud.kms_v1.types.service import AsymmetricSignRequest +from google.cloud.kms_v1.types.service import AsymmetricSignResponse +from google.cloud.kms_v1.types.service import CreateCryptoKeyRequest +from google.cloud.kms_v1.types.service import CreateCryptoKeyVersionRequest +from google.cloud.kms_v1.types.service import CreateImportJobRequest +from google.cloud.kms_v1.types.service import CreateKeyRingRequest +from google.cloud.kms_v1.types.service import DecryptRequest +from google.cloud.kms_v1.types.service import DecryptResponse +from google.cloud.kms_v1.types.service import DestroyCryptoKeyVersionRequest +from google.cloud.kms_v1.types.service import Digest +from google.cloud.kms_v1.types.service import EncryptRequest +from google.cloud.kms_v1.types.service import EncryptResponse +from google.cloud.kms_v1.types.service import GenerateRandomBytesRequest +from google.cloud.kms_v1.types.service import GenerateRandomBytesResponse +from google.cloud.kms_v1.types.service import GetCryptoKeyRequest +from google.cloud.kms_v1.types.service import GetCryptoKeyVersionRequest +from google.cloud.kms_v1.types.service import GetImportJobRequest +from google.cloud.kms_v1.types.service import GetKeyRingRequest +from google.cloud.kms_v1.types.service import GetPublicKeyRequest +from google.cloud.kms_v1.types.service import ImportCryptoKeyVersionRequest +from google.cloud.kms_v1.types.service import ListCryptoKeysRequest +from google.cloud.kms_v1.types.service import ListCryptoKeysResponse +from google.cloud.kms_v1.types.service import ListCryptoKeyVersionsRequest +from google.cloud.kms_v1.types.service import ListCryptoKeyVersionsResponse +from google.cloud.kms_v1.types.service import ListImportJobsRequest +from google.cloud.kms_v1.types.service import ListImportJobsResponse +from google.cloud.kms_v1.types.service import ListKeyRingsRequest +from google.cloud.kms_v1.types.service import ListKeyRingsResponse +from google.cloud.kms_v1.types.service import LocationMetadata +from google.cloud.kms_v1.types.service import MacSignRequest +from google.cloud.kms_v1.types.service import MacSignResponse +from google.cloud.kms_v1.types.service import MacVerifyRequest +from google.cloud.kms_v1.types.service import MacVerifyResponse +from google.cloud.kms_v1.types.service import RawDecryptRequest +from google.cloud.kms_v1.types.service import RawDecryptResponse +from google.cloud.kms_v1.types.service import RawEncryptRequest +from google.cloud.kms_v1.types.service import RawEncryptResponse +from google.cloud.kms_v1.types.service import RestoreCryptoKeyVersionRequest +from google.cloud.kms_v1.types.service import UpdateCryptoKeyPrimaryVersionRequest +from google.cloud.kms_v1.types.service import UpdateCryptoKeyRequest +from google.cloud.kms_v1.types.service import UpdateCryptoKeyVersionRequest + +__all__ = ('AutokeyClient', + 'AutokeyAsyncClient', + 'AutokeyAdminClient', + 'AutokeyAdminAsyncClient', + 'EkmServiceClient', + 'EkmServiceAsyncClient', + 'KeyManagementServiceClient', + 'KeyManagementServiceAsyncClient', + 'CreateKeyHandleMetadata', + 'CreateKeyHandleRequest', + 'GetKeyHandleRequest', + 'KeyHandle', + 'ListKeyHandlesRequest', + 'ListKeyHandlesResponse', + 'AutokeyConfig', + 'GetAutokeyConfigRequest', + 'ShowEffectiveAutokeyConfigRequest', + 'ShowEffectiveAutokeyConfigResponse', + 'UpdateAutokeyConfigRequest', + 'Certificate', + 'CreateEkmConnectionRequest', + 'EkmConfig', + 'EkmConnection', + 'GetEkmConfigRequest', + 'GetEkmConnectionRequest', + 'ListEkmConnectionsRequest', + 'ListEkmConnectionsResponse', + 'UpdateEkmConfigRequest', + 'UpdateEkmConnectionRequest', + 'VerifyConnectivityRequest', + 'VerifyConnectivityResponse', + 'CryptoKey', + 'CryptoKeyVersion', + 'CryptoKeyVersionTemplate', + 'ExternalProtectionLevelOptions', + 'ImportJob', + 'KeyAccessJustificationsPolicy', + 'KeyOperationAttestation', + 'KeyRing', + 'PublicKey', + 'AccessReason', + 'ProtectionLevel', + 'AsymmetricDecryptRequest', + 'AsymmetricDecryptResponse', + 'AsymmetricSignRequest', + 'AsymmetricSignResponse', + 'CreateCryptoKeyRequest', + 'CreateCryptoKeyVersionRequest', + 'CreateImportJobRequest', + 'CreateKeyRingRequest', + 'DecryptRequest', + 'DecryptResponse', + 'DestroyCryptoKeyVersionRequest', + 'Digest', + 'EncryptRequest', + 'EncryptResponse', + 'GenerateRandomBytesRequest', + 'GenerateRandomBytesResponse', + 'GetCryptoKeyRequest', + 'GetCryptoKeyVersionRequest', + 'GetImportJobRequest', + 'GetKeyRingRequest', + 'GetPublicKeyRequest', + 'ImportCryptoKeyVersionRequest', + 'ListCryptoKeysRequest', + 'ListCryptoKeysResponse', + 'ListCryptoKeyVersionsRequest', + 'ListCryptoKeyVersionsResponse', + 'ListImportJobsRequest', + 'ListImportJobsResponse', + 'ListKeyRingsRequest', + 'ListKeyRingsResponse', + 'LocationMetadata', + 'MacSignRequest', + 'MacSignResponse', + 'MacVerifyRequest', + 'MacVerifyResponse', + 'RawDecryptRequest', + 'RawDecryptResponse', + 'RawEncryptRequest', + 'RawEncryptResponse', + 'RestoreCryptoKeyVersionRequest', + 'UpdateCryptoKeyPrimaryVersionRequest', + 'UpdateCryptoKeyRequest', + 'UpdateCryptoKeyVersionRequest', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/gapic_version.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/py.typed b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/py.typed new file mode 100644 index 000000000000..3720b5f23ae9 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-kms package uses inline types. diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/__init__.py new file mode 100644 index 000000000000..2ad2f667cccc --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/__init__.py @@ -0,0 +1,194 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.kms_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.autokey import AutokeyClient +from .services.autokey import AutokeyAsyncClient +from .services.autokey_admin import AutokeyAdminClient +from .services.autokey_admin import AutokeyAdminAsyncClient +from .services.ekm_service import EkmServiceClient +from .services.ekm_service import EkmServiceAsyncClient +from .services.key_management_service import KeyManagementServiceClient +from .services.key_management_service import KeyManagementServiceAsyncClient + +from .types.autokey import CreateKeyHandleMetadata +from .types.autokey import CreateKeyHandleRequest +from .types.autokey import GetKeyHandleRequest +from .types.autokey import KeyHandle +from .types.autokey import ListKeyHandlesRequest +from .types.autokey import ListKeyHandlesResponse +from .types.autokey_admin import AutokeyConfig +from .types.autokey_admin import GetAutokeyConfigRequest +from .types.autokey_admin import ShowEffectiveAutokeyConfigRequest +from .types.autokey_admin import ShowEffectiveAutokeyConfigResponse +from .types.autokey_admin import UpdateAutokeyConfigRequest +from .types.ekm_service import Certificate +from .types.ekm_service import CreateEkmConnectionRequest +from .types.ekm_service import EkmConfig +from .types.ekm_service import EkmConnection +from .types.ekm_service import GetEkmConfigRequest +from .types.ekm_service import GetEkmConnectionRequest +from .types.ekm_service import ListEkmConnectionsRequest +from .types.ekm_service import ListEkmConnectionsResponse +from .types.ekm_service import UpdateEkmConfigRequest +from .types.ekm_service import UpdateEkmConnectionRequest +from .types.ekm_service import VerifyConnectivityRequest +from .types.ekm_service import VerifyConnectivityResponse +from .types.resources import CryptoKey +from .types.resources import CryptoKeyVersion +from .types.resources import CryptoKeyVersionTemplate +from .types.resources import ExternalProtectionLevelOptions +from .types.resources import ImportJob +from .types.resources import KeyAccessJustificationsPolicy +from .types.resources import KeyOperationAttestation +from .types.resources import KeyRing +from .types.resources import PublicKey +from .types.resources import AccessReason +from .types.resources import ProtectionLevel +from .types.service import AsymmetricDecryptRequest +from .types.service import AsymmetricDecryptResponse +from .types.service import AsymmetricSignRequest +from .types.service import AsymmetricSignResponse +from .types.service import CreateCryptoKeyRequest +from .types.service import CreateCryptoKeyVersionRequest +from .types.service import CreateImportJobRequest +from .types.service import CreateKeyRingRequest +from .types.service import DecryptRequest +from .types.service import DecryptResponse +from .types.service import DestroyCryptoKeyVersionRequest +from .types.service import Digest +from .types.service import EncryptRequest +from .types.service import EncryptResponse +from .types.service import GenerateRandomBytesRequest +from .types.service import GenerateRandomBytesResponse +from .types.service import GetCryptoKeyRequest +from .types.service import GetCryptoKeyVersionRequest +from .types.service import GetImportJobRequest +from .types.service import GetKeyRingRequest +from .types.service import GetPublicKeyRequest +from .types.service import ImportCryptoKeyVersionRequest +from .types.service import ListCryptoKeysRequest +from .types.service import ListCryptoKeysResponse +from .types.service import ListCryptoKeyVersionsRequest +from .types.service import ListCryptoKeyVersionsResponse +from .types.service import ListImportJobsRequest +from .types.service import ListImportJobsResponse +from .types.service import ListKeyRingsRequest +from .types.service import ListKeyRingsResponse +from .types.service import LocationMetadata +from .types.service import MacSignRequest +from .types.service import MacSignResponse +from .types.service import MacVerifyRequest +from .types.service import MacVerifyResponse +from .types.service import RawDecryptRequest +from .types.service import RawDecryptResponse +from .types.service import RawEncryptRequest +from .types.service import RawEncryptResponse +from .types.service import RestoreCryptoKeyVersionRequest +from .types.service import UpdateCryptoKeyPrimaryVersionRequest +from .types.service import UpdateCryptoKeyRequest +from .types.service import UpdateCryptoKeyVersionRequest + +__all__ = ( + 'AutokeyAdminAsyncClient', + 'AutokeyAsyncClient', + 'EkmServiceAsyncClient', + 'KeyManagementServiceAsyncClient', +'AccessReason', +'AsymmetricDecryptRequest', +'AsymmetricDecryptResponse', +'AsymmetricSignRequest', +'AsymmetricSignResponse', +'AutokeyAdminClient', +'AutokeyClient', +'AutokeyConfig', +'Certificate', +'CreateCryptoKeyRequest', +'CreateCryptoKeyVersionRequest', +'CreateEkmConnectionRequest', +'CreateImportJobRequest', +'CreateKeyHandleMetadata', +'CreateKeyHandleRequest', +'CreateKeyRingRequest', +'CryptoKey', +'CryptoKeyVersion', +'CryptoKeyVersionTemplate', +'DecryptRequest', +'DecryptResponse', +'DestroyCryptoKeyVersionRequest', +'Digest', +'EkmConfig', +'EkmConnection', +'EkmServiceClient', +'EncryptRequest', +'EncryptResponse', +'ExternalProtectionLevelOptions', +'GenerateRandomBytesRequest', +'GenerateRandomBytesResponse', +'GetAutokeyConfigRequest', +'GetCryptoKeyRequest', +'GetCryptoKeyVersionRequest', +'GetEkmConfigRequest', +'GetEkmConnectionRequest', +'GetImportJobRequest', +'GetKeyHandleRequest', +'GetKeyRingRequest', +'GetPublicKeyRequest', +'ImportCryptoKeyVersionRequest', +'ImportJob', +'KeyAccessJustificationsPolicy', +'KeyHandle', +'KeyManagementServiceClient', +'KeyOperationAttestation', +'KeyRing', +'ListCryptoKeyVersionsRequest', +'ListCryptoKeyVersionsResponse', +'ListCryptoKeysRequest', +'ListCryptoKeysResponse', +'ListEkmConnectionsRequest', +'ListEkmConnectionsResponse', +'ListImportJobsRequest', +'ListImportJobsResponse', +'ListKeyHandlesRequest', +'ListKeyHandlesResponse', +'ListKeyRingsRequest', +'ListKeyRingsResponse', +'LocationMetadata', +'MacSignRequest', +'MacSignResponse', +'MacVerifyRequest', +'MacVerifyResponse', +'ProtectionLevel', +'PublicKey', +'RawDecryptRequest', +'RawDecryptResponse', +'RawEncryptRequest', +'RawEncryptResponse', +'RestoreCryptoKeyVersionRequest', +'ShowEffectiveAutokeyConfigRequest', +'ShowEffectiveAutokeyConfigResponse', +'UpdateAutokeyConfigRequest', +'UpdateCryptoKeyPrimaryVersionRequest', +'UpdateCryptoKeyRequest', +'UpdateCryptoKeyVersionRequest', +'UpdateEkmConfigRequest', +'UpdateEkmConnectionRequest', +'VerifyConnectivityRequest', +'VerifyConnectivityResponse', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_metadata.json new file mode 100644 index 000000000000..4d760054fd94 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_metadata.json @@ -0,0 +1,700 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.kms_v1", + "protoPackage": "google.cloud.kms.v1", + "schema": "1.0", + "services": { + "Autokey": { + "clients": { + "grpc": { + "libraryClient": "AutokeyClient", + "rpcs": { + "CreateKeyHandle": { + "methods": [ + "create_key_handle" + ] + }, + "GetKeyHandle": { + "methods": [ + "get_key_handle" + ] + }, + "ListKeyHandles": { + "methods": [ + "list_key_handles" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AutokeyAsyncClient", + "rpcs": { + "CreateKeyHandle": { + "methods": [ + "create_key_handle" + ] + }, + "GetKeyHandle": { + "methods": [ + "get_key_handle" + ] + }, + "ListKeyHandles": { + "methods": [ + "list_key_handles" + ] + } + } + }, + "rest": { + "libraryClient": "AutokeyClient", + "rpcs": { + "CreateKeyHandle": { + "methods": [ + "create_key_handle" + ] + }, + "GetKeyHandle": { + "methods": [ + "get_key_handle" + ] + }, + "ListKeyHandles": { + "methods": [ + "list_key_handles" + ] + } + } + } + } + }, + "AutokeyAdmin": { + "clients": { + "grpc": { + "libraryClient": "AutokeyAdminClient", + "rpcs": { + "GetAutokeyConfig": { + "methods": [ + "get_autokey_config" + ] + }, + "ShowEffectiveAutokeyConfig": { + "methods": [ + "show_effective_autokey_config" + ] + }, + "UpdateAutokeyConfig": { + "methods": [ + "update_autokey_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AutokeyAdminAsyncClient", + "rpcs": { + "GetAutokeyConfig": { + "methods": [ + "get_autokey_config" + ] + }, + "ShowEffectiveAutokeyConfig": { + "methods": [ + "show_effective_autokey_config" + ] + }, + "UpdateAutokeyConfig": { + "methods": [ + "update_autokey_config" + ] + } + } + }, + "rest": { + "libraryClient": "AutokeyAdminClient", + "rpcs": { + "GetAutokeyConfig": { + "methods": [ + "get_autokey_config" + ] + }, + "ShowEffectiveAutokeyConfig": { + "methods": [ + "show_effective_autokey_config" + ] + }, + "UpdateAutokeyConfig": { + "methods": [ + "update_autokey_config" + ] + } + } + } + } + }, + "EkmService": { + "clients": { + "grpc": { + "libraryClient": "EkmServiceClient", + "rpcs": { + "CreateEkmConnection": { + "methods": [ + "create_ekm_connection" + ] + }, + "GetEkmConfig": { + "methods": [ + "get_ekm_config" + ] + }, + "GetEkmConnection": { + "methods": [ + "get_ekm_connection" + ] + }, + "ListEkmConnections": { + "methods": [ + "list_ekm_connections" + ] + }, + "UpdateEkmConfig": { + "methods": [ + "update_ekm_config" + ] + }, + "UpdateEkmConnection": { + "methods": [ + "update_ekm_connection" + ] + }, + "VerifyConnectivity": { + "methods": [ + "verify_connectivity" + ] + } + } + }, + "grpc-async": { + "libraryClient": "EkmServiceAsyncClient", + "rpcs": { + "CreateEkmConnection": { + "methods": [ + "create_ekm_connection" + ] + }, + "GetEkmConfig": { + "methods": [ + "get_ekm_config" + ] + }, + "GetEkmConnection": { + "methods": [ + "get_ekm_connection" + ] + }, + "ListEkmConnections": { + "methods": [ + "list_ekm_connections" + ] + }, + "UpdateEkmConfig": { + "methods": [ + "update_ekm_config" + ] + }, + "UpdateEkmConnection": { + "methods": [ + "update_ekm_connection" + ] + }, + "VerifyConnectivity": { + "methods": [ + "verify_connectivity" + ] + } + } + }, + "rest": { + "libraryClient": "EkmServiceClient", + "rpcs": { + "CreateEkmConnection": { + "methods": [ + "create_ekm_connection" + ] + }, + "GetEkmConfig": { + "methods": [ + "get_ekm_config" + ] + }, + "GetEkmConnection": { + "methods": [ + "get_ekm_connection" + ] + }, + "ListEkmConnections": { + "methods": [ + "list_ekm_connections" + ] + }, + "UpdateEkmConfig": { + "methods": [ + "update_ekm_config" + ] + }, + "UpdateEkmConnection": { + "methods": [ + "update_ekm_connection" + ] + }, + "VerifyConnectivity": { + "methods": [ + "verify_connectivity" + ] + } + } + } + } + }, + "KeyManagementService": { + "clients": { + "grpc": { + "libraryClient": "KeyManagementServiceClient", + "rpcs": { + "AsymmetricDecrypt": { + "methods": [ + "asymmetric_decrypt" + ] + }, + "AsymmetricSign": { + "methods": [ + "asymmetric_sign" + ] + }, + "CreateCryptoKey": { + "methods": [ + "create_crypto_key" + ] + }, + "CreateCryptoKeyVersion": { + "methods": [ + "create_crypto_key_version" + ] + }, + "CreateImportJob": { + "methods": [ + "create_import_job" + ] + }, + "CreateKeyRing": { + "methods": [ + "create_key_ring" + ] + }, + "Decrypt": { + "methods": [ + "decrypt" + ] + }, + "DestroyCryptoKeyVersion": { + "methods": [ + "destroy_crypto_key_version" + ] + }, + "Encrypt": { + "methods": [ + "encrypt" + ] + }, + "GenerateRandomBytes": { + "methods": [ + "generate_random_bytes" + ] + }, + "GetCryptoKey": { + "methods": [ + "get_crypto_key" + ] + }, + "GetCryptoKeyVersion": { + "methods": [ + "get_crypto_key_version" + ] + }, + "GetImportJob": { + "methods": [ + "get_import_job" + ] + }, + "GetKeyRing": { + "methods": [ + "get_key_ring" + ] + }, + "GetPublicKey": { + "methods": [ + "get_public_key" + ] + }, + "ImportCryptoKeyVersion": { + "methods": [ + "import_crypto_key_version" + ] + }, + "ListCryptoKeyVersions": { + "methods": [ + "list_crypto_key_versions" + ] + }, + "ListCryptoKeys": { + "methods": [ + "list_crypto_keys" + ] + }, + "ListImportJobs": { + "methods": [ + "list_import_jobs" + ] + }, + "ListKeyRings": { + "methods": [ + "list_key_rings" + ] + }, + "MacSign": { + "methods": [ + "mac_sign" + ] + }, + "MacVerify": { + "methods": [ + "mac_verify" + ] + }, + "RawDecrypt": { + "methods": [ + "raw_decrypt" + ] + }, + "RawEncrypt": { + "methods": [ + "raw_encrypt" + ] + }, + "RestoreCryptoKeyVersion": { + "methods": [ + "restore_crypto_key_version" + ] + }, + "UpdateCryptoKey": { + "methods": [ + "update_crypto_key" + ] + }, + "UpdateCryptoKeyPrimaryVersion": { + "methods": [ + "update_crypto_key_primary_version" + ] + }, + "UpdateCryptoKeyVersion": { + "methods": [ + "update_crypto_key_version" + ] + } + } + }, + "grpc-async": { + "libraryClient": "KeyManagementServiceAsyncClient", + "rpcs": { + "AsymmetricDecrypt": { + "methods": [ + "asymmetric_decrypt" + ] + }, + "AsymmetricSign": { + "methods": [ + "asymmetric_sign" + ] + }, + "CreateCryptoKey": { + "methods": [ + "create_crypto_key" + ] + }, + "CreateCryptoKeyVersion": { + "methods": [ + "create_crypto_key_version" + ] + }, + "CreateImportJob": { + "methods": [ + "create_import_job" + ] + }, + "CreateKeyRing": { + "methods": [ + "create_key_ring" + ] + }, + "Decrypt": { + "methods": [ + "decrypt" + ] + }, + "DestroyCryptoKeyVersion": { + "methods": [ + "destroy_crypto_key_version" + ] + }, + "Encrypt": { + "methods": [ + "encrypt" + ] + }, + "GenerateRandomBytes": { + "methods": [ + "generate_random_bytes" + ] + }, + "GetCryptoKey": { + "methods": [ + "get_crypto_key" + ] + }, + "GetCryptoKeyVersion": { + "methods": [ + "get_crypto_key_version" + ] + }, + "GetImportJob": { + "methods": [ + "get_import_job" + ] + }, + "GetKeyRing": { + "methods": [ + "get_key_ring" + ] + }, + "GetPublicKey": { + "methods": [ + "get_public_key" + ] + }, + "ImportCryptoKeyVersion": { + "methods": [ + "import_crypto_key_version" + ] + }, + "ListCryptoKeyVersions": { + "methods": [ + "list_crypto_key_versions" + ] + }, + "ListCryptoKeys": { + "methods": [ + "list_crypto_keys" + ] + }, + "ListImportJobs": { + "methods": [ + "list_import_jobs" + ] + }, + "ListKeyRings": { + "methods": [ + "list_key_rings" + ] + }, + "MacSign": { + "methods": [ + "mac_sign" + ] + }, + "MacVerify": { + "methods": [ + "mac_verify" + ] + }, + "RawDecrypt": { + "methods": [ + "raw_decrypt" + ] + }, + "RawEncrypt": { + "methods": [ + "raw_encrypt" + ] + }, + "RestoreCryptoKeyVersion": { + "methods": [ + "restore_crypto_key_version" + ] + }, + "UpdateCryptoKey": { + "methods": [ + "update_crypto_key" + ] + }, + "UpdateCryptoKeyPrimaryVersion": { + "methods": [ + "update_crypto_key_primary_version" + ] + }, + "UpdateCryptoKeyVersion": { + "methods": [ + "update_crypto_key_version" + ] + } + } + }, + "rest": { + "libraryClient": "KeyManagementServiceClient", + "rpcs": { + "AsymmetricDecrypt": { + "methods": [ + "asymmetric_decrypt" + ] + }, + "AsymmetricSign": { + "methods": [ + "asymmetric_sign" + ] + }, + "CreateCryptoKey": { + "methods": [ + "create_crypto_key" + ] + }, + "CreateCryptoKeyVersion": { + "methods": [ + "create_crypto_key_version" + ] + }, + "CreateImportJob": { + "methods": [ + "create_import_job" + ] + }, + "CreateKeyRing": { + "methods": [ + "create_key_ring" + ] + }, + "Decrypt": { + "methods": [ + "decrypt" + ] + }, + "DestroyCryptoKeyVersion": { + "methods": [ + "destroy_crypto_key_version" + ] + }, + "Encrypt": { + "methods": [ + "encrypt" + ] + }, + "GenerateRandomBytes": { + "methods": [ + "generate_random_bytes" + ] + }, + "GetCryptoKey": { + "methods": [ + "get_crypto_key" + ] + }, + "GetCryptoKeyVersion": { + "methods": [ + "get_crypto_key_version" + ] + }, + "GetImportJob": { + "methods": [ + "get_import_job" + ] + }, + "GetKeyRing": { + "methods": [ + "get_key_ring" + ] + }, + "GetPublicKey": { + "methods": [ + "get_public_key" + ] + }, + "ImportCryptoKeyVersion": { + "methods": [ + "import_crypto_key_version" + ] + }, + "ListCryptoKeyVersions": { + "methods": [ + "list_crypto_key_versions" + ] + }, + "ListCryptoKeys": { + "methods": [ + "list_crypto_keys" + ] + }, + "ListImportJobs": { + "methods": [ + "list_import_jobs" + ] + }, + "ListKeyRings": { + "methods": [ + "list_key_rings" + ] + }, + "MacSign": { + "methods": [ + "mac_sign" + ] + }, + "MacVerify": { + "methods": [ + "mac_verify" + ] + }, + "RawDecrypt": { + "methods": [ + "raw_decrypt" + ] + }, + "RawEncrypt": { + "methods": [ + "raw_encrypt" + ] + }, + "RestoreCryptoKeyVersion": { + "methods": [ + "restore_crypto_key_version" + ] + }, + "UpdateCryptoKey": { + "methods": [ + "update_crypto_key" + ] + }, + "UpdateCryptoKeyPrimaryVersion": { + "methods": [ + "update_crypto_key_primary_version" + ] + }, + "UpdateCryptoKeyVersion": { + "methods": [ + "update_crypto_key_version" + ] + } + } + } + } + } + } +} diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_version.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/py.typed b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/py.typed new file mode 100644 index 000000000000..3720b5f23ae9 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-kms package uses inline types. diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/__init__.py new file mode 100644 index 000000000000..4875c51e6dea --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AutokeyClient +from .async_client import AutokeyAsyncClient + +__all__ = ( + 'AutokeyClient', + 'AutokeyAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/async_client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/async_client.py new file mode 100644 index 000000000000..e8ffd3bdf912 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/async_client.py @@ -0,0 +1,1074 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.kms_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.kms_v1.services.autokey import pagers +from google.cloud.kms_v1.types import autokey +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import AutokeyTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AutokeyGrpcAsyncIOTransport +from .client import AutokeyClient + + +class AutokeyAsyncClient: + """Provides interfaces for using `Cloud KMS + Autokey `__ to provision + new [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer + Managed Encryption Key (CMEK) use, on-demand. To support certain + client tooling, this feature is modeled around a + [KeyHandle][google.cloud.kms.v1.KeyHandle] resource: creating a + [KeyHandle][google.cloud.kms.v1.KeyHandle] in a resource project and + given location triggers Cloud KMS Autokey to provision a + [CryptoKey][google.cloud.kms.v1.CryptoKey] in the configured key + project and the same location. + + Prior to use in a given resource project, + [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig] + should have been called on an ancestor folder, setting the key + project where Cloud KMS Autokey should create new + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. See documentation for + additional prerequisites. To check what key project, if any, is + currently configured on a resource project's ancestor folder, see + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + """ + + _client: AutokeyClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AutokeyClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AutokeyClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AutokeyClient._DEFAULT_UNIVERSE + + crypto_key_path = staticmethod(AutokeyClient.crypto_key_path) + parse_crypto_key_path = staticmethod(AutokeyClient.parse_crypto_key_path) + key_handle_path = staticmethod(AutokeyClient.key_handle_path) + parse_key_handle_path = staticmethod(AutokeyClient.parse_key_handle_path) + common_billing_account_path = staticmethod(AutokeyClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AutokeyClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AutokeyClient.common_folder_path) + parse_common_folder_path = staticmethod(AutokeyClient.parse_common_folder_path) + common_organization_path = staticmethod(AutokeyClient.common_organization_path) + parse_common_organization_path = staticmethod(AutokeyClient.parse_common_organization_path) + common_project_path = staticmethod(AutokeyClient.common_project_path) + parse_common_project_path = staticmethod(AutokeyClient.parse_common_project_path) + common_location_path = staticmethod(AutokeyClient.common_location_path) + parse_common_location_path = staticmethod(AutokeyClient.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: + AutokeyAsyncClient: The constructed client. + """ + return AutokeyClient.from_service_account_info.__func__(AutokeyAsyncClient, 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: + AutokeyAsyncClient: The constructed client. + """ + return AutokeyClient.from_service_account_file.__func__(AutokeyAsyncClient, 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 AutokeyClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AutokeyTransport: + """Returns the transport used by the client instance. + + Returns: + AutokeyTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = AutokeyClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AutokeyTransport, Callable[..., AutokeyTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the autokey async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AutokeyTransport,Callable[..., AutokeyTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AutokeyTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AutokeyClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def create_key_handle(self, + request: Optional[Union[autokey.CreateKeyHandleRequest, dict]] = None, + *, + parent: Optional[str] = None, + key_handle: Optional[autokey.KeyHandle] = None, + key_handle_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new [KeyHandle][google.cloud.kms.v1.KeyHandle], + triggering the provisioning of a new + [CryptoKey][google.cloud.kms.v1.CryptoKey] for CMEK use with the + given resource type in the configured key project and the same + location. [GetOperation][Operations.GetOperation] should be used + to resolve the resulting long-running operation and get the + resulting [KeyHandle][google.cloud.kms.v1.KeyHandle] and + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_create_key_handle(): + # Create a client + client = kms_v1.AutokeyAsyncClient() + + # Initialize request argument(s) + key_handle = kms_v1.KeyHandle() + key_handle.resource_type_selector = "resource_type_selector_value" + + request = kms_v1.CreateKeyHandleRequest( + parent="parent_value", + key_handle=key_handle, + ) + + # Make the request + operation = client.create_key_handle(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.CreateKeyHandleRequest, dict]]): + The request object. Request message for + [Autokey.CreateKeyHandle][google.cloud.kms.v1.Autokey.CreateKeyHandle]. + parent (:class:`str`): + Required. Name of the resource project and location to + create the [KeyHandle][google.cloud.kms.v1.KeyHandle] + in, e.g. ``projects/{PROJECT_ID}/locations/{LOCATION}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_handle (:class:`google.cloud.kms_v1.types.KeyHandle`): + Required. [KeyHandle][google.cloud.kms.v1.KeyHandle] to + create. + + This corresponds to the ``key_handle`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_handle_id (:class:`str`): + Optional. Id of the + [KeyHandle][google.cloud.kms.v1.KeyHandle]. Must be + unique to the resource project and location. If not + provided by the caller, a new UUID is used. + + This corresponds to the ``key_handle_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.kms_v1.types.KeyHandle` Resource-oriented representation of a request to Cloud KMS Autokey and the + resulting provisioning of a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, key_handle, key_handle_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey.CreateKeyHandleRequest): + request = autokey.CreateKeyHandleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if key_handle is not None: + request.key_handle = key_handle + if key_handle_id is not None: + request.key_handle_id = key_handle_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_key_handle] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + autokey.KeyHandle, + metadata_type=autokey.CreateKeyHandleMetadata, + ) + + # Done; return the response. + return response + + async def get_key_handle(self, + request: Optional[Union[autokey.GetKeyHandleRequest, 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]] = (), + ) -> autokey.KeyHandle: + r"""Returns the [KeyHandle][google.cloud.kms.v1.KeyHandle]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_get_key_handle(): + # Create a client + client = kms_v1.AutokeyAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetKeyHandleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_key_handle(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GetKeyHandleRequest, dict]]): + The request object. Request message for + [GetKeyHandle][google.cloud.kms.v1.Autokey.GetKeyHandle]. + name (:class:`str`): + Required. Name of the + [KeyHandle][google.cloud.kms.v1.KeyHandle] resource, + e.g. + ``projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.KeyHandle: + Resource-oriented representation of a request to Cloud KMS Autokey and the + resulting provisioning of a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey.GetKeyHandleRequest): + request = autokey.GetKeyHandleRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_key_handle] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_key_handles(self, + request: Optional[Union[autokey.ListKeyHandlesRequest, 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.ListKeyHandlesAsyncPager: + r"""Lists [KeyHandles][google.cloud.kms.v1.KeyHandle]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_list_key_handles(): + # Create a client + client = kms_v1.AutokeyAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListKeyHandlesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_handles(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ListKeyHandlesRequest, dict]]): + The request object. Request message for + [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. + parent (:class:`str`): + Required. Name of the resource project and location from + which to list + [KeyHandles][google.cloud.kms.v1.KeyHandle], e.g. + ``projects/{PROJECT_ID}/locations/{LOCATION}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.services.autokey.pagers.ListKeyHandlesAsyncPager: + Response message for + [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey.ListKeyHandlesRequest): + request = autokey.ListKeyHandlesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_key_handles] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListKeyHandlesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does + not have a policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified permissions against the IAM access control + policy for a function. + + If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~iam_policy_pb2.PolicyTestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AutokeyAsyncClient": + 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__ = ( + "AutokeyAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/client.py new file mode 100644 index 000000000000..01dde42c7d5a --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/client.py @@ -0,0 +1,1423 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.kms_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.cloud.kms_v1.services.autokey import pagers +from google.cloud.kms_v1.types import autokey +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .transports.base import AutokeyTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AutokeyGrpcTransport +from .transports.grpc_asyncio import AutokeyGrpcAsyncIOTransport +from .transports.rest import AutokeyRestTransport + + +class AutokeyClientMeta(type): + """Metaclass for the Autokey 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[AutokeyTransport]] + _transport_registry["grpc"] = AutokeyGrpcTransport + _transport_registry["grpc_asyncio"] = AutokeyGrpcAsyncIOTransport + _transport_registry["rest"] = AutokeyRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AutokeyTransport]: + """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 AutokeyClient(metaclass=AutokeyClientMeta): + """Provides interfaces for using `Cloud KMS + Autokey `__ to provision + new [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer + Managed Encryption Key (CMEK) use, on-demand. To support certain + client tooling, this feature is modeled around a + [KeyHandle][google.cloud.kms.v1.KeyHandle] resource: creating a + [KeyHandle][google.cloud.kms.v1.KeyHandle] in a resource project and + given location triggers Cloud KMS Autokey to provision a + [CryptoKey][google.cloud.kms.v1.CryptoKey] in the configured key + project and the same location. + + Prior to use in a given resource project, + [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig] + should have been called on an ancestor folder, setting the key + project where Cloud KMS Autokey should create new + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. See documentation for + additional prerequisites. To check what key project, if any, is + currently configured on a resource project's ancestor folder, see + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "cloudkms.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudkms.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AutokeyClient: 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: + AutokeyClient: 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) -> AutokeyTransport: + """Returns the transport used by the client instance. + + Returns: + AutokeyTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str,str]: + """Parses a crypto_key path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def key_handle_path(project: str,location: str,key_handle: str,) -> str: + """Returns a fully-qualified key_handle string.""" + return "projects/{project}/locations/{location}/keyHandles/{key_handle}".format(project=project, location=location, key_handle=key_handle, ) + + @staticmethod + def parse_key_handle_path(path: str) -> Dict[str,str]: + """Parses a key_handle path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyHandles/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = AutokeyClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AutokeyClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AutokeyClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AutokeyTransport, Callable[..., AutokeyTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the autokey client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AutokeyTransport,Callable[..., AutokeyTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AutokeyTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AutokeyClient._read_environment_variables() + self._client_cert_source = AutokeyClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AutokeyClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AutokeyTransport) + if transport_provided: + # transport is a AutokeyTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(AutokeyTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AutokeyClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[AutokeyTransport], Callable[..., AutokeyTransport]] = ( + AutokeyClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AutokeyTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def create_key_handle(self, + request: Optional[Union[autokey.CreateKeyHandleRequest, dict]] = None, + *, + parent: Optional[str] = None, + key_handle: Optional[autokey.KeyHandle] = None, + key_handle_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new [KeyHandle][google.cloud.kms.v1.KeyHandle], + triggering the provisioning of a new + [CryptoKey][google.cloud.kms.v1.CryptoKey] for CMEK use with the + given resource type in the configured key project and the same + location. [GetOperation][Operations.GetOperation] should be used + to resolve the resulting long-running operation and get the + resulting [KeyHandle][google.cloud.kms.v1.KeyHandle] and + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_create_key_handle(): + # Create a client + client = kms_v1.AutokeyClient() + + # Initialize request argument(s) + key_handle = kms_v1.KeyHandle() + key_handle.resource_type_selector = "resource_type_selector_value" + + request = kms_v1.CreateKeyHandleRequest( + parent="parent_value", + key_handle=key_handle, + ) + + # Make the request + operation = client.create_key_handle(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.CreateKeyHandleRequest, dict]): + The request object. Request message for + [Autokey.CreateKeyHandle][google.cloud.kms.v1.Autokey.CreateKeyHandle]. + parent (str): + Required. Name of the resource project and location to + create the [KeyHandle][google.cloud.kms.v1.KeyHandle] + in, e.g. ``projects/{PROJECT_ID}/locations/{LOCATION}``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_handle (google.cloud.kms_v1.types.KeyHandle): + Required. [KeyHandle][google.cloud.kms.v1.KeyHandle] to + create. + + This corresponds to the ``key_handle`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_handle_id (str): + Optional. Id of the + [KeyHandle][google.cloud.kms.v1.KeyHandle]. Must be + unique to the resource project and location. If not + provided by the caller, a new UUID is used. + + This corresponds to the ``key_handle_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.kms_v1.types.KeyHandle` Resource-oriented representation of a request to Cloud KMS Autokey and the + resulting provisioning of a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, key_handle, key_handle_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey.CreateKeyHandleRequest): + request = autokey.CreateKeyHandleRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if key_handle is not None: + request.key_handle = key_handle + if key_handle_id is not None: + request.key_handle_id = key_handle_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_key_handle] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + autokey.KeyHandle, + metadata_type=autokey.CreateKeyHandleMetadata, + ) + + # Done; return the response. + return response + + def get_key_handle(self, + request: Optional[Union[autokey.GetKeyHandleRequest, 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]] = (), + ) -> autokey.KeyHandle: + r"""Returns the [KeyHandle][google.cloud.kms.v1.KeyHandle]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_get_key_handle(): + # Create a client + client = kms_v1.AutokeyClient() + + # Initialize request argument(s) + request = kms_v1.GetKeyHandleRequest( + name="name_value", + ) + + # Make the request + response = client.get_key_handle(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GetKeyHandleRequest, dict]): + The request object. Request message for + [GetKeyHandle][google.cloud.kms.v1.Autokey.GetKeyHandle]. + name (str): + Required. Name of the + [KeyHandle][google.cloud.kms.v1.KeyHandle] resource, + e.g. + ``projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}``. + + 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.kms_v1.types.KeyHandle: + Resource-oriented representation of a request to Cloud KMS Autokey and the + resulting provisioning of a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey.GetKeyHandleRequest): + request = autokey.GetKeyHandleRequest(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_key_handle] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_key_handles(self, + request: Optional[Union[autokey.ListKeyHandlesRequest, 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.ListKeyHandlesPager: + r"""Lists [KeyHandles][google.cloud.kms.v1.KeyHandle]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_list_key_handles(): + # Create a client + client = kms_v1.AutokeyClient() + + # Initialize request argument(s) + request = kms_v1.ListKeyHandlesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_handles(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ListKeyHandlesRequest, dict]): + The request object. Request message for + [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. + parent (str): + Required. Name of the resource project and location from + which to list + [KeyHandles][google.cloud.kms.v1.KeyHandle], e.g. + ``projects/{PROJECT_ID}/locations/{LOCATION}``. + + 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.kms_v1.services.autokey.pagers.ListKeyHandlesPager: + Response message for + [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey.ListKeyHandlesRequest): + request = autokey.ListKeyHandlesRequest(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_key_handles] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListKeyHandlesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AutokeyClient": + 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 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 = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AutokeyClient", +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/pagers.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/pagers.py new file mode 100644 index 000000000000..774a3ee84746 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.kms_v1.types import autokey + + +class ListKeyHandlesPager: + """A pager for iterating through ``list_key_handles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListKeyHandlesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``key_handles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListKeyHandles`` requests and continue to iterate + through the ``key_handles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListKeyHandlesResponse` + 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[..., autokey.ListKeyHandlesResponse], + request: autokey.ListKeyHandlesRequest, + response: autokey.ListKeyHandlesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListKeyHandlesRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListKeyHandlesResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = autokey.ListKeyHandlesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[autokey.ListKeyHandlesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[autokey.KeyHandle]: + for page in self.pages: + yield from page.key_handles + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListKeyHandlesAsyncPager: + """A pager for iterating through ``list_key_handles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListKeyHandlesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``key_handles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListKeyHandles`` requests and continue to iterate + through the ``key_handles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListKeyHandlesResponse` + 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[autokey.ListKeyHandlesResponse]], + request: autokey.ListKeyHandlesRequest, + response: autokey.ListKeyHandlesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListKeyHandlesRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListKeyHandlesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = autokey.ListKeyHandlesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[autokey.ListKeyHandlesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[autokey.KeyHandle]: + async def async_generator(): + async for page in self.pages: + for response in page.key_handles: + 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-kms/v1/google/cloud/kms_v1/services/autokey/transports/README.rst b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/README.rst new file mode 100644 index 000000000000..e6b77aacde54 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AutokeyTransport` is the ABC for all transports. +- public child `AutokeyGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AutokeyGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAutokeyRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AutokeyRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/__init__.py new file mode 100644 index 000000000000..c53d2840ddd7 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AutokeyTransport +from .grpc import AutokeyGrpcTransport +from .grpc_asyncio import AutokeyGrpcAsyncIOTransport +from .rest import AutokeyRestTransport +from .rest import AutokeyRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AutokeyTransport]] +_transport_registry['grpc'] = AutokeyGrpcTransport +_transport_registry['grpc_asyncio'] = AutokeyGrpcAsyncIOTransport +_transport_registry['rest'] = AutokeyRestTransport + +__all__ = ( + 'AutokeyTransport', + 'AutokeyGrpcTransport', + 'AutokeyGrpcAsyncIOTransport', + 'AutokeyRestTransport', + 'AutokeyRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/base.py new file mode 100644 index 000000000000..d5cb99f09a57 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/base.py @@ -0,0 +1,298 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.kms_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.kms_v1.types import autokey +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AutokeyTransport(abc.ABC): + """Abstract transport class for Autokey.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', + ) + + DEFAULT_HOST: str = 'cloudkms.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_key_handle: gapic_v1.method.wrap_method( + self.create_key_handle, + default_timeout=60.0, + client_info=client_info, + ), + self.get_key_handle: gapic_v1.method.wrap_method( + self.get_key_handle, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_key_handles: gapic_v1.method.wrap_method( + self.list_key_handles, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + 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_key_handle(self) -> Callable[ + [autokey.CreateKeyHandleRequest], + Union[ + operations_pb2.Operation, + Awaitable[operations_pb2.Operation] + ]]: + raise NotImplementedError() + + @property + def get_key_handle(self) -> Callable[ + [autokey.GetKeyHandleRequest], + Union[ + autokey.KeyHandle, + Awaitable[autokey.KeyHandle] + ]]: + raise NotImplementedError() + + @property + def list_key_handles(self) -> Callable[ + [autokey.ListKeyHandlesRequest], + Union[ + autokey.ListKeyHandlesResponse, + Awaitable[autokey.ListKeyHandlesResponse] + ]]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AutokeyTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc.py new file mode 100644 index 000000000000..fff0485d8ea3 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc.py @@ -0,0 +1,502 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.kms_v1.types import autokey +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import AutokeyTransport, DEFAULT_CLIENT_INFO + + +class AutokeyGrpcTransport(AutokeyTransport): + """gRPC backend transport for Autokey. + + Provides interfaces for using `Cloud KMS + Autokey `__ to provision + new [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer + Managed Encryption Key (CMEK) use, on-demand. To support certain + client tooling, this feature is modeled around a + [KeyHandle][google.cloud.kms.v1.KeyHandle] resource: creating a + [KeyHandle][google.cloud.kms.v1.KeyHandle] in a resource project and + given location triggers Cloud KMS Autokey to provision a + [CryptoKey][google.cloud.kms.v1.CryptoKey] in the configured key + project and the same location. + + Prior to use in a given resource project, + [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig] + should have been called on an ancestor folder, setting the key + project where Cloud KMS Autokey should create new + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. See documentation for + additional prerequisites. To check what key project, if any, is + currently configured on a resource project's ancestor folder, see + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + + 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 = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudkms.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_key_handle(self) -> Callable[ + [autokey.CreateKeyHandleRequest], + operations_pb2.Operation]: + r"""Return a callable for the create key handle method over gRPC. + + Creates a new [KeyHandle][google.cloud.kms.v1.KeyHandle], + triggering the provisioning of a new + [CryptoKey][google.cloud.kms.v1.CryptoKey] for CMEK use with the + given resource type in the configured key project and the same + location. [GetOperation][Operations.GetOperation] should be used + to resolve the resulting long-running operation and get the + resulting [KeyHandle][google.cloud.kms.v1.KeyHandle] and + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.CreateKeyHandleRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_handle' not in self._stubs: + self._stubs['create_key_handle'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.Autokey/CreateKeyHandle', + request_serializer=autokey.CreateKeyHandleRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_key_handle'] + + @property + def get_key_handle(self) -> Callable[ + [autokey.GetKeyHandleRequest], + autokey.KeyHandle]: + r"""Return a callable for the get key handle method over gRPC. + + Returns the [KeyHandle][google.cloud.kms.v1.KeyHandle]. + + Returns: + Callable[[~.GetKeyHandleRequest], + ~.KeyHandle]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_handle' not in self._stubs: + self._stubs['get_key_handle'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.Autokey/GetKeyHandle', + request_serializer=autokey.GetKeyHandleRequest.serialize, + response_deserializer=autokey.KeyHandle.deserialize, + ) + return self._stubs['get_key_handle'] + + @property + def list_key_handles(self) -> Callable[ + [autokey.ListKeyHandlesRequest], + autokey.ListKeyHandlesResponse]: + r"""Return a callable for the list key handles method over gRPC. + + Lists [KeyHandles][google.cloud.kms.v1.KeyHandle]. + + Returns: + Callable[[~.ListKeyHandlesRequest], + ~.ListKeyHandlesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_handles' not in self._stubs: + self._stubs['list_key_handles'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.Autokey/ListKeyHandles', + request_serializer=autokey.ListKeyHandlesRequest.serialize, + response_deserializer=autokey.ListKeyHandlesResponse.deserialize, + ) + return self._stubs['list_key_handles'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def close(self): + self.grpc_channel.close() + + @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_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AutokeyGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc_asyncio.py new file mode 100644 index 000000000000..5c98c65a9d14 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc_asyncio.py @@ -0,0 +1,584 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.api_core import operations_v1 +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.kms_v1.types import autokey +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import AutokeyTransport, DEFAULT_CLIENT_INFO +from .grpc import AutokeyGrpcTransport + + +class AutokeyGrpcAsyncIOTransport(AutokeyTransport): + """gRPC AsyncIO backend transport for Autokey. + + Provides interfaces for using `Cloud KMS + Autokey `__ to provision + new [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer + Managed Encryption Key (CMEK) use, on-demand. To support certain + client tooling, this feature is modeled around a + [KeyHandle][google.cloud.kms.v1.KeyHandle] resource: creating a + [KeyHandle][google.cloud.kms.v1.KeyHandle] in a resource project and + given location triggers Cloud KMS Autokey to provision a + [CryptoKey][google.cloud.kms.v1.CryptoKey] in the configured key + project and the same location. + + Prior to use in a given resource project, + [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig] + should have been called on an ancestor folder, setting the key + project where Cloud KMS Autokey should create new + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. See documentation for + additional prerequisites. To check what key project, if any, is + currently configured on a resource project's ancestor folder, see + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + + 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 = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_key_handle(self) -> Callable[ + [autokey.CreateKeyHandleRequest], + Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the create key handle method over gRPC. + + Creates a new [KeyHandle][google.cloud.kms.v1.KeyHandle], + triggering the provisioning of a new + [CryptoKey][google.cloud.kms.v1.CryptoKey] for CMEK use with the + given resource type in the configured key project and the same + location. [GetOperation][Operations.GetOperation] should be used + to resolve the resulting long-running operation and get the + resulting [KeyHandle][google.cloud.kms.v1.KeyHandle] and + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.CreateKeyHandleRequest], + 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_key_handle' not in self._stubs: + self._stubs['create_key_handle'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.Autokey/CreateKeyHandle', + request_serializer=autokey.CreateKeyHandleRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs['create_key_handle'] + + @property + def get_key_handle(self) -> Callable[ + [autokey.GetKeyHandleRequest], + Awaitable[autokey.KeyHandle]]: + r"""Return a callable for the get key handle method over gRPC. + + Returns the [KeyHandle][google.cloud.kms.v1.KeyHandle]. + + Returns: + Callable[[~.GetKeyHandleRequest], + Awaitable[~.KeyHandle]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_handle' not in self._stubs: + self._stubs['get_key_handle'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.Autokey/GetKeyHandle', + request_serializer=autokey.GetKeyHandleRequest.serialize, + response_deserializer=autokey.KeyHandle.deserialize, + ) + return self._stubs['get_key_handle'] + + @property + def list_key_handles(self) -> Callable[ + [autokey.ListKeyHandlesRequest], + Awaitable[autokey.ListKeyHandlesResponse]]: + r"""Return a callable for the list key handles method over gRPC. + + Lists [KeyHandles][google.cloud.kms.v1.KeyHandle]. + + Returns: + Callable[[~.ListKeyHandlesRequest], + Awaitable[~.ListKeyHandlesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_handles' not in self._stubs: + self._stubs['list_key_handles'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.Autokey/ListKeyHandles', + request_serializer=autokey.ListKeyHandlesRequest.serialize, + response_deserializer=autokey.ListKeyHandlesResponse.deserialize, + ) + return self._stubs['list_key_handles'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_key_handle: self._wrap_method( + self.create_key_handle, + default_timeout=60.0, + client_info=client_info, + ), + self.get_key_handle: self._wrap_method( + self.get_key_handle, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_key_handles: self._wrap_method( + self.list_key_handles, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @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_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ( + 'AutokeyGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest.py new file mode 100644 index 000000000000..90947de10822 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest.py @@ -0,0 +1,1119 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.api_core import operations_v1 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.kms_v1.types import autokey +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseAutokeyRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class AutokeyRestInterceptor: + """Interceptor for Autokey. + + 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 AutokeyRestTransport. + + .. code-block:: python + class MyCustomAutokeyInterceptor(AutokeyRestInterceptor): + def pre_create_key_handle(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_key_handle(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_key_handle(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_key_handle(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_key_handles(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_key_handles(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AutokeyRestTransport(interceptor=MyCustomAutokeyInterceptor()) + client = AutokeyClient(transport=transport) + + + """ + def pre_create_key_handle(self, request: autokey.CreateKeyHandleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey.CreateKeyHandleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_key_handle + + Override in a subclass to manipulate the request or metadata + before they are sent to the Autokey server. + """ + return request, metadata + + def post_create_key_handle(self, response: operations_pb2.Operation) -> operations_pb2.Operation: + """Post-rpc interceptor for create_key_handle + + Override in a subclass to manipulate the response + after it is returned by the Autokey server but before + it is returned to user code. + """ + return response + + def pre_get_key_handle(self, request: autokey.GetKeyHandleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey.GetKeyHandleRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_key_handle + + Override in a subclass to manipulate the request or metadata + before they are sent to the Autokey server. + """ + return request, metadata + + def post_get_key_handle(self, response: autokey.KeyHandle) -> autokey.KeyHandle: + """Post-rpc interceptor for get_key_handle + + Override in a subclass to manipulate the response + after it is returned by the Autokey server but before + it is returned to user code. + """ + return response + + def pre_list_key_handles(self, request: autokey.ListKeyHandlesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey.ListKeyHandlesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_key_handles + + Override in a subclass to manipulate the request or metadata + before they are sent to the Autokey server. + """ + return request, metadata + + def post_list_key_handles(self, response: autokey.ListKeyHandlesResponse) -> autokey.ListKeyHandlesResponse: + """Post-rpc interceptor for list_key_handles + + Override in a subclass to manipulate the response + after it is returned by the Autokey server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Autokey server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the Autokey server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Autokey server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the Autokey server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Autokey server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Autokey server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the Autokey server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the Autokey server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the Autokey server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the Autokey 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 Autokey 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 Autokey server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AutokeyRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AutokeyRestInterceptor + + +class AutokeyRestTransport(_BaseAutokeyRestTransport): + """REST backend synchronous transport for Autokey. + + Provides interfaces for using `Cloud KMS + Autokey `__ to provision + new [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer + Managed Encryption Key (CMEK) use, on-demand. To support certain + client tooling, this feature is modeled around a + [KeyHandle][google.cloud.kms.v1.KeyHandle] resource: creating a + [KeyHandle][google.cloud.kms.v1.KeyHandle] in a resource project and + given location triggers Cloud KMS Autokey to provision a + [CryptoKey][google.cloud.kms.v1.CryptoKey] in the configured key + project and the same location. + + Prior to use in a given resource project, + [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig] + should have been called on an ancestor folder, setting the key + project where Cloud KMS Autokey should create new + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. See documentation for + additional prerequisites. To check what key project, if any, is + currently configured on a resource project's ancestor folder, see + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + + 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 = 'cloudkms.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[AutokeyRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AutokeyRestInterceptor() + 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.GetOperation': [ + { + '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 _CreateKeyHandle(_BaseAutokeyRestTransport._BaseCreateKeyHandle, AutokeyRestStub): + def __hash__(self): + return hash("AutokeyRestTransport.CreateKeyHandle") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: autokey.CreateKeyHandleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> operations_pb2.Operation: + r"""Call the create key handle method over HTTP. + + Args: + request (~.autokey.CreateKeyHandleRequest): + The request object. Request message for + [Autokey.CreateKeyHandle][google.cloud.kms.v1.Autokey.CreateKeyHandle]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + 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 = _BaseAutokeyRestTransport._BaseCreateKeyHandle._get_http_options() + request, metadata = self._interceptor.pre_create_key_handle(request, metadata) + transcoded_request = _BaseAutokeyRestTransport._BaseCreateKeyHandle._get_transcoded_request(http_options, request) + + body = _BaseAutokeyRestTransport._BaseCreateKeyHandle._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAutokeyRestTransport._BaseCreateKeyHandle._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyRestTransport._CreateKeyHandle._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_key_handle(resp) + return resp + + class _GetKeyHandle(_BaseAutokeyRestTransport._BaseGetKeyHandle, AutokeyRestStub): + def __hash__(self): + return hash("AutokeyRestTransport.GetKeyHandle") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: autokey.GetKeyHandleRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> autokey.KeyHandle: + r"""Call the get key handle method over HTTP. + + Args: + request (~.autokey.GetKeyHandleRequest): + The request object. Request message for + [GetKeyHandle][google.cloud.kms.v1.Autokey.GetKeyHandle]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.autokey.KeyHandle: + Resource-oriented representation of a request to Cloud + KMS Autokey and the resulting provisioning of a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + """ + + http_options = _BaseAutokeyRestTransport._BaseGetKeyHandle._get_http_options() + request, metadata = self._interceptor.pre_get_key_handle(request, metadata) + transcoded_request = _BaseAutokeyRestTransport._BaseGetKeyHandle._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyRestTransport._BaseGetKeyHandle._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyRestTransport._GetKeyHandle._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = autokey.KeyHandle() + pb_resp = autokey.KeyHandle.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_key_handle(resp) + return resp + + class _ListKeyHandles(_BaseAutokeyRestTransport._BaseListKeyHandles, AutokeyRestStub): + def __hash__(self): + return hash("AutokeyRestTransport.ListKeyHandles") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: autokey.ListKeyHandlesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> autokey.ListKeyHandlesResponse: + r"""Call the list key handles method over HTTP. + + Args: + request (~.autokey.ListKeyHandlesRequest): + The request object. Request message for + [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.autokey.ListKeyHandlesResponse: + Response message for + [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. + + """ + + http_options = _BaseAutokeyRestTransport._BaseListKeyHandles._get_http_options() + request, metadata = self._interceptor.pre_list_key_handles(request, metadata) + transcoded_request = _BaseAutokeyRestTransport._BaseListKeyHandles._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyRestTransport._BaseListKeyHandles._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyRestTransport._ListKeyHandles._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = autokey.ListKeyHandlesResponse() + pb_resp = autokey.ListKeyHandlesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_key_handles(resp) + return resp + + @property + def create_key_handle(self) -> Callable[ + [autokey.CreateKeyHandleRequest], + 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._CreateKeyHandle(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_key_handle(self) -> Callable[ + [autokey.GetKeyHandleRequest], + autokey.KeyHandle]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetKeyHandle(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_key_handles(self) -> Callable[ + [autokey.ListKeyHandlesRequest], + autokey.ListKeyHandlesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListKeyHandles(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseAutokeyRestTransport._BaseGetLocation, AutokeyRestStub): + def __hash__(self): + return hash("AutokeyRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseAutokeyRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseAutokeyRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseAutokeyRestTransport._BaseListLocations, AutokeyRestStub): + def __hash__(self): + return hash("AutokeyRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseAutokeyRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseAutokeyRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseAutokeyRestTransport._BaseGetIamPolicy, AutokeyRestStub): + def __hash__(self): + return hash("AutokeyRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseAutokeyRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseAutokeyRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseAutokeyRestTransport._BaseSetIamPolicy, AutokeyRestStub): + def __hash__(self): + return hash("AutokeyRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseAutokeyRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseAutokeyRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseAutokeyRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAutokeyRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseAutokeyRestTransport._BaseTestIamPermissions, AutokeyRestStub): + def __hash__(self): + return hash("AutokeyRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseAutokeyRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseAutokeyRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseAutokeyRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAutokeyRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseAutokeyRestTransport._BaseGetOperation, AutokeyRestStub): + def __hash__(self): + return hash("AutokeyRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, 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 = _BaseAutokeyRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseAutokeyRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AutokeyRestTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest_base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest_base.py new file mode 100644 index 000000000000..f2801b90062f --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest_base.py @@ -0,0 +1,434 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import AutokeyTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.kms_v1.types import autokey +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseAutokeyRestTransport(AutokeyTransport): + """Base REST backend transport for Autokey. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'cloudkms.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseCreateKeyHandle: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/keyHandles', + 'body': 'key_handle', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = autokey.CreateKeyHandleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAutokeyRestTransport._BaseCreateKeyHandle._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetKeyHandle: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/keyHandles/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = autokey.GetKeyHandleRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAutokeyRestTransport._BaseGetKeyHandle._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListKeyHandles: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/keyHandles', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = autokey.ListKeyHandlesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAutokeyRestTransport._BaseListKeyHandles._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:getIamPolicy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseAutokeyRestTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/__init__.py new file mode 100644 index 000000000000..da33906ea63a --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import AutokeyAdminClient +from .async_client import AutokeyAdminAsyncClient + +__all__ = ( + 'AutokeyAdminClient', + 'AutokeyAdminAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/async_client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/async_client.py new file mode 100644 index 000000000000..8c98490639ad --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/async_client.py @@ -0,0 +1,1018 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.kms_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.kms_v1.types import autokey_admin +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import AutokeyAdminTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import AutokeyAdminGrpcAsyncIOTransport +from .client import AutokeyAdminClient + + +class AutokeyAdminAsyncClient: + """Provides interfaces for managing `Cloud KMS + Autokey `__ folder-level + configurations. A configuration is inherited by all descendent + projects. A configuration at one folder overrides any other + configurations in its ancestry. Setting a configuration on a folder + is a prerequisite for Cloud KMS Autokey, so that users working in a + descendant project can request provisioned + [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer + Managed Encryption Key (CMEK) use, on-demand. + """ + + _client: AutokeyAdminClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AutokeyAdminClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AutokeyAdminClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AutokeyAdminClient._DEFAULT_UNIVERSE + + autokey_config_path = staticmethod(AutokeyAdminClient.autokey_config_path) + parse_autokey_config_path = staticmethod(AutokeyAdminClient.parse_autokey_config_path) + common_billing_account_path = staticmethod(AutokeyAdminClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(AutokeyAdminClient.parse_common_billing_account_path) + common_folder_path = staticmethod(AutokeyAdminClient.common_folder_path) + parse_common_folder_path = staticmethod(AutokeyAdminClient.parse_common_folder_path) + common_organization_path = staticmethod(AutokeyAdminClient.common_organization_path) + parse_common_organization_path = staticmethod(AutokeyAdminClient.parse_common_organization_path) + common_project_path = staticmethod(AutokeyAdminClient.common_project_path) + parse_common_project_path = staticmethod(AutokeyAdminClient.parse_common_project_path) + common_location_path = staticmethod(AutokeyAdminClient.common_location_path) + parse_common_location_path = staticmethod(AutokeyAdminClient.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: + AutokeyAdminAsyncClient: The constructed client. + """ + return AutokeyAdminClient.from_service_account_info.__func__(AutokeyAdminAsyncClient, 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: + AutokeyAdminAsyncClient: The constructed client. + """ + return AutokeyAdminClient.from_service_account_file.__func__(AutokeyAdminAsyncClient, 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 AutokeyAdminClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AutokeyAdminTransport: + """Returns the transport used by the client instance. + + Returns: + AutokeyAdminTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = AutokeyAdminClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AutokeyAdminTransport, Callable[..., AutokeyAdminTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the autokey admin async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AutokeyAdminTransport,Callable[..., AutokeyAdminTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AutokeyAdminTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AutokeyAdminClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def update_autokey_config(self, + request: Optional[Union[autokey_admin.UpdateAutokeyConfigRequest, dict]] = None, + *, + autokey_config: Optional[autokey_admin.AutokeyConfig] = 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]] = (), + ) -> autokey_admin.AutokeyConfig: + r"""Updates the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] + for a folder. The caller must have both + ``cloudkms.autokeyConfigs.update`` permission on the parent + folder and ``cloudkms.cryptoKeys.setIamPolicy`` permission on + the provided key project. A + [KeyHandle][google.cloud.kms.v1.KeyHandle] creation in the + folder's descendant projects will use this configuration to + determine where to create the resulting + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_update_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateAutokeyConfigRequest( + ) + + # Make the request + response = await client.update_autokey_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.UpdateAutokeyConfigRequest, dict]]): + The request object. Request message for + [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig]. + autokey_config (:class:`google.cloud.kms_v1.types.AutokeyConfig`): + Required. + [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] with + values to update. + + This corresponds to the ``autokey_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. Masks which fields of the + [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] to + update, e.g. ``keyProject``. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.AutokeyConfig: + Cloud KMS Autokey configuration for a + folder. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([autokey_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey_admin.UpdateAutokeyConfigRequest): + request = autokey_admin.UpdateAutokeyConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if autokey_config is not None: + request.autokey_config = autokey_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_autokey_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("autokey_config.name", request.autokey_config.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_autokey_config(self, + request: Optional[Union[autokey_admin.GetAutokeyConfigRequest, 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]] = (), + ) -> autokey_admin.AutokeyConfig: + r"""Returns the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] + for a folder. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_get_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetAutokeyConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_autokey_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GetAutokeyConfigRequest, dict]]): + The request object. Request message for + [GetAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig]. + name (:class:`str`): + Required. Name of the + [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] + resource, e.g. + ``folders/{FOLDER_NUMBER}/autokeyConfig``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.AutokeyConfig: + Cloud KMS Autokey configuration for a + folder. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey_admin.GetAutokeyConfigRequest): + request = autokey_admin.GetAutokeyConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_autokey_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def show_effective_autokey_config(self, + request: Optional[Union[autokey_admin.ShowEffectiveAutokeyConfigRequest, 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]] = (), + ) -> autokey_admin.ShowEffectiveAutokeyConfigResponse: + r"""Returns the effective Cloud KMS Autokey configuration + for a given project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_show_effective_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ShowEffectiveAutokeyConfigRequest( + parent="parent_value", + ) + + # Make the request + response = await client.show_effective_autokey_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ShowEffectiveAutokeyConfigRequest, dict]]): + The request object. Request message for + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + parent (:class:`str`): + Required. Name of the resource + project to the show effective Cloud KMS + Autokey configuration for. This may be + helpful for interrogating the effect of + nested folder configurations on a given + resource project. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.ShowEffectiveAutokeyConfigResponse: + Response message for + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey_admin.ShowEffectiveAutokeyConfigRequest): + request = autokey_admin.ShowEffectiveAutokeyConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.show_effective_autokey_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does + not have a policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified permissions against the IAM access control + policy for a function. + + If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~iam_policy_pb2.PolicyTestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "AutokeyAdminAsyncClient": + 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__ = ( + "AutokeyAdminAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/client.py new file mode 100644 index 000000000000..b0a447fce811 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/client.py @@ -0,0 +1,1358 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.kms_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.cloud.kms_v1.types import autokey_admin +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from .transports.base import AutokeyAdminTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import AutokeyAdminGrpcTransport +from .transports.grpc_asyncio import AutokeyAdminGrpcAsyncIOTransport +from .transports.rest import AutokeyAdminRestTransport + + +class AutokeyAdminClientMeta(type): + """Metaclass for the AutokeyAdmin 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[AutokeyAdminTransport]] + _transport_registry["grpc"] = AutokeyAdminGrpcTransport + _transport_registry["grpc_asyncio"] = AutokeyAdminGrpcAsyncIOTransport + _transport_registry["rest"] = AutokeyAdminRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[AutokeyAdminTransport]: + """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 AutokeyAdminClient(metaclass=AutokeyAdminClientMeta): + """Provides interfaces for managing `Cloud KMS + Autokey `__ folder-level + configurations. A configuration is inherited by all descendent + projects. A configuration at one folder overrides any other + configurations in its ancestry. Setting a configuration on a folder + is a prerequisite for Cloud KMS Autokey, so that users working in a + descendant project can request provisioned + [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer + Managed Encryption Key (CMEK) use, on-demand. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "cloudkms.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudkms.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AutokeyAdminClient: 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: + AutokeyAdminClient: 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) -> AutokeyAdminTransport: + """Returns the transport used by the client instance. + + Returns: + AutokeyAdminTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def autokey_config_path(folder: str,) -> str: + """Returns a fully-qualified autokey_config string.""" + return "folders/{folder}/autokeyConfig".format(folder=folder, ) + + @staticmethod + def parse_autokey_config_path(path: str) -> Dict[str,str]: + """Parses a autokey_config path into its component segments.""" + m = re.match(r"^folders/(?P.+?)/autokeyConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = AutokeyAdminClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = AutokeyAdminClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = AutokeyAdminClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, AutokeyAdminTransport, Callable[..., AutokeyAdminTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the autokey admin client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AutokeyAdminTransport,Callable[..., AutokeyAdminTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AutokeyAdminTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AutokeyAdminClient._read_environment_variables() + self._client_cert_source = AutokeyAdminClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = AutokeyAdminClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, AutokeyAdminTransport) + if transport_provided: + # transport is a AutokeyAdminTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(AutokeyAdminTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + AutokeyAdminClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[AutokeyAdminTransport], Callable[..., AutokeyAdminTransport]] = ( + AutokeyAdminClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AutokeyAdminTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def update_autokey_config(self, + request: Optional[Union[autokey_admin.UpdateAutokeyConfigRequest, dict]] = None, + *, + autokey_config: Optional[autokey_admin.AutokeyConfig] = 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]] = (), + ) -> autokey_admin.AutokeyConfig: + r"""Updates the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] + for a folder. The caller must have both + ``cloudkms.autokeyConfigs.update`` permission on the parent + folder and ``cloudkms.cryptoKeys.setIamPolicy`` permission on + the provided key project. A + [KeyHandle][google.cloud.kms.v1.KeyHandle] creation in the + folder's descendant projects will use this configuration to + determine where to create the resulting + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_update_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminClient() + + # Initialize request argument(s) + request = kms_v1.UpdateAutokeyConfigRequest( + ) + + # Make the request + response = client.update_autokey_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.UpdateAutokeyConfigRequest, dict]): + The request object. Request message for + [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig]. + autokey_config (google.cloud.kms_v1.types.AutokeyConfig): + Required. + [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] with + values to update. + + This corresponds to the ``autokey_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Masks which fields of the + [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] to + update, e.g. ``keyProject``. + + 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.cloud.kms_v1.types.AutokeyConfig: + Cloud KMS Autokey configuration for a + folder. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([autokey_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey_admin.UpdateAutokeyConfigRequest): + request = autokey_admin.UpdateAutokeyConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if autokey_config is not None: + request.autokey_config = autokey_config + 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_autokey_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("autokey_config.name", request.autokey_config.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_autokey_config(self, + request: Optional[Union[autokey_admin.GetAutokeyConfigRequest, 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]] = (), + ) -> autokey_admin.AutokeyConfig: + r"""Returns the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] + for a folder. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_get_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminClient() + + # Initialize request argument(s) + request = kms_v1.GetAutokeyConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_autokey_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GetAutokeyConfigRequest, dict]): + The request object. Request message for + [GetAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig]. + name (str): + Required. Name of the + [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] + resource, e.g. + ``folders/{FOLDER_NUMBER}/autokeyConfig``. + + 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.kms_v1.types.AutokeyConfig: + Cloud KMS Autokey configuration for a + folder. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey_admin.GetAutokeyConfigRequest): + request = autokey_admin.GetAutokeyConfigRequest(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_autokey_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def show_effective_autokey_config(self, + request: Optional[Union[autokey_admin.ShowEffectiveAutokeyConfigRequest, 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]] = (), + ) -> autokey_admin.ShowEffectiveAutokeyConfigResponse: + r"""Returns the effective Cloud KMS Autokey configuration + for a given project. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_show_effective_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminClient() + + # Initialize request argument(s) + request = kms_v1.ShowEffectiveAutokeyConfigRequest( + parent="parent_value", + ) + + # Make the request + response = client.show_effective_autokey_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ShowEffectiveAutokeyConfigRequest, dict]): + The request object. Request message for + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + parent (str): + Required. Name of the resource + project to the show effective Cloud KMS + Autokey configuration for. This may be + helpful for interrogating the effect of + nested folder configurations on a given + resource project. + + 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.kms_v1.types.ShowEffectiveAutokeyConfigResponse: + Response message for + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, autokey_admin.ShowEffectiveAutokeyConfigRequest): + request = autokey_admin.ShowEffectiveAutokeyConfigRequest(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.show_effective_autokey_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "AutokeyAdminClient": + 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 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 = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "AutokeyAdminClient", +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/README.rst b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/README.rst new file mode 100644 index 000000000000..e031a9fac606 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`AutokeyAdminTransport` is the ABC for all transports. +- public child `AutokeyAdminGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `AutokeyAdminGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseAutokeyAdminRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `AutokeyAdminRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/__init__.py new file mode 100644 index 000000000000..16792e9f9d1a --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import AutokeyAdminTransport +from .grpc import AutokeyAdminGrpcTransport +from .grpc_asyncio import AutokeyAdminGrpcAsyncIOTransport +from .rest import AutokeyAdminRestTransport +from .rest import AutokeyAdminRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AutokeyAdminTransport]] +_transport_registry['grpc'] = AutokeyAdminGrpcTransport +_transport_registry['grpc_asyncio'] = AutokeyAdminGrpcAsyncIOTransport +_transport_registry['rest'] = AutokeyAdminRestTransport + +__all__ = ( + 'AutokeyAdminTransport', + 'AutokeyAdminGrpcTransport', + 'AutokeyAdminGrpcAsyncIOTransport', + 'AutokeyAdminRestTransport', + 'AutokeyAdminRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/base.py new file mode 100644 index 000000000000..b70e09688a7e --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/base.py @@ -0,0 +1,302 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.kms_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.kms_v1.types import autokey_admin +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class AutokeyAdminTransport(abc.ABC): + """Abstract transport class for AutokeyAdmin.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', + ) + + DEFAULT_HOST: str = 'cloudkms.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.update_autokey_config: gapic_v1.method.wrap_method( + self.update_autokey_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_autokey_config: gapic_v1.method.wrap_method( + self.get_autokey_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.show_effective_autokey_config: gapic_v1.method.wrap_method( + self.show_effective_autokey_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + 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 update_autokey_config(self) -> Callable[ + [autokey_admin.UpdateAutokeyConfigRequest], + Union[ + autokey_admin.AutokeyConfig, + Awaitable[autokey_admin.AutokeyConfig] + ]]: + raise NotImplementedError() + + @property + def get_autokey_config(self) -> Callable[ + [autokey_admin.GetAutokeyConfigRequest], + Union[ + autokey_admin.AutokeyConfig, + Awaitable[autokey_admin.AutokeyConfig] + ]]: + raise NotImplementedError() + + @property + def show_effective_autokey_config(self) -> Callable[ + [autokey_admin.ShowEffectiveAutokeyConfigRequest], + Union[ + autokey_admin.ShowEffectiveAutokeyConfigResponse, + Awaitable[autokey_admin.ShowEffectiveAutokeyConfigResponse] + ]]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'AutokeyAdminTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc.py new file mode 100644 index 000000000000..dc3ee2da4098 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc.py @@ -0,0 +1,477 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.kms_v1.types import autokey_admin +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import AutokeyAdminTransport, DEFAULT_CLIENT_INFO + + +class AutokeyAdminGrpcTransport(AutokeyAdminTransport): + """gRPC backend transport for AutokeyAdmin. + + Provides interfaces for managing `Cloud KMS + Autokey `__ folder-level + configurations. A configuration is inherited by all descendent + projects. A configuration at one folder overrides any other + configurations in its ancestry. Setting a configuration on a folder + is a prerequisite for Cloud KMS Autokey, so that users working in a + descendant project can request provisioned + [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer + Managed Encryption Key (CMEK) use, on-demand. + + 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 = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudkms.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 update_autokey_config(self) -> Callable[ + [autokey_admin.UpdateAutokeyConfigRequest], + autokey_admin.AutokeyConfig]: + r"""Return a callable for the update autokey config method over gRPC. + + Updates the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] + for a folder. The caller must have both + ``cloudkms.autokeyConfigs.update`` permission on the parent + folder and ``cloudkms.cryptoKeys.setIamPolicy`` permission on + the provided key project. A + [KeyHandle][google.cloud.kms.v1.KeyHandle] creation in the + folder's descendant projects will use this configuration to + determine where to create the resulting + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.UpdateAutokeyConfigRequest], + ~.AutokeyConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_autokey_config' not in self._stubs: + self._stubs['update_autokey_config'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.AutokeyAdmin/UpdateAutokeyConfig', + request_serializer=autokey_admin.UpdateAutokeyConfigRequest.serialize, + response_deserializer=autokey_admin.AutokeyConfig.deserialize, + ) + return self._stubs['update_autokey_config'] + + @property + def get_autokey_config(self) -> Callable[ + [autokey_admin.GetAutokeyConfigRequest], + autokey_admin.AutokeyConfig]: + r"""Return a callable for the get autokey config method over gRPC. + + Returns the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] + for a folder. + + Returns: + Callable[[~.GetAutokeyConfigRequest], + ~.AutokeyConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_autokey_config' not in self._stubs: + self._stubs['get_autokey_config'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.AutokeyAdmin/GetAutokeyConfig', + request_serializer=autokey_admin.GetAutokeyConfigRequest.serialize, + response_deserializer=autokey_admin.AutokeyConfig.deserialize, + ) + return self._stubs['get_autokey_config'] + + @property + def show_effective_autokey_config(self) -> Callable[ + [autokey_admin.ShowEffectiveAutokeyConfigRequest], + autokey_admin.ShowEffectiveAutokeyConfigResponse]: + r"""Return a callable for the show effective autokey config method over gRPC. + + Returns the effective Cloud KMS Autokey configuration + for a given project. + + Returns: + Callable[[~.ShowEffectiveAutokeyConfigRequest], + ~.ShowEffectiveAutokeyConfigResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'show_effective_autokey_config' not in self._stubs: + self._stubs['show_effective_autokey_config'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.AutokeyAdmin/ShowEffectiveAutokeyConfig', + request_serializer=autokey_admin.ShowEffectiveAutokeyConfigRequest.serialize, + response_deserializer=autokey_admin.ShowEffectiveAutokeyConfigResponse.deserialize, + ) + return self._stubs['show_effective_autokey_config'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def close(self): + self.grpc_channel.close() + + @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_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'AutokeyAdminGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc_asyncio.py new file mode 100644 index 000000000000..68e7a9fb896d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc_asyncio.py @@ -0,0 +1,569 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.kms_v1.types import autokey_admin +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import AutokeyAdminTransport, DEFAULT_CLIENT_INFO +from .grpc import AutokeyAdminGrpcTransport + + +class AutokeyAdminGrpcAsyncIOTransport(AutokeyAdminTransport): + """gRPC AsyncIO backend transport for AutokeyAdmin. + + Provides interfaces for managing `Cloud KMS + Autokey `__ folder-level + configurations. A configuration is inherited by all descendent + projects. A configuration at one folder overrides any other + configurations in its ancestry. Setting a configuration on a folder + is a prerequisite for Cloud KMS Autokey, so that users working in a + descendant project can request provisioned + [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer + Managed Encryption Key (CMEK) use, on-demand. + + 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 = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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 update_autokey_config(self) -> Callable[ + [autokey_admin.UpdateAutokeyConfigRequest], + Awaitable[autokey_admin.AutokeyConfig]]: + r"""Return a callable for the update autokey config method over gRPC. + + Updates the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] + for a folder. The caller must have both + ``cloudkms.autokeyConfigs.update`` permission on the parent + folder and ``cloudkms.cryptoKeys.setIamPolicy`` permission on + the provided key project. A + [KeyHandle][google.cloud.kms.v1.KeyHandle] creation in the + folder's descendant projects will use this configuration to + determine where to create the resulting + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.UpdateAutokeyConfigRequest], + Awaitable[~.AutokeyConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_autokey_config' not in self._stubs: + self._stubs['update_autokey_config'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.AutokeyAdmin/UpdateAutokeyConfig', + request_serializer=autokey_admin.UpdateAutokeyConfigRequest.serialize, + response_deserializer=autokey_admin.AutokeyConfig.deserialize, + ) + return self._stubs['update_autokey_config'] + + @property + def get_autokey_config(self) -> Callable[ + [autokey_admin.GetAutokeyConfigRequest], + Awaitable[autokey_admin.AutokeyConfig]]: + r"""Return a callable for the get autokey config method over gRPC. + + Returns the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] + for a folder. + + Returns: + Callable[[~.GetAutokeyConfigRequest], + Awaitable[~.AutokeyConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_autokey_config' not in self._stubs: + self._stubs['get_autokey_config'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.AutokeyAdmin/GetAutokeyConfig', + request_serializer=autokey_admin.GetAutokeyConfigRequest.serialize, + response_deserializer=autokey_admin.AutokeyConfig.deserialize, + ) + return self._stubs['get_autokey_config'] + + @property + def show_effective_autokey_config(self) -> Callable[ + [autokey_admin.ShowEffectiveAutokeyConfigRequest], + Awaitable[autokey_admin.ShowEffectiveAutokeyConfigResponse]]: + r"""Return a callable for the show effective autokey config method over gRPC. + + Returns the effective Cloud KMS Autokey configuration + for a given project. + + Returns: + Callable[[~.ShowEffectiveAutokeyConfigRequest], + Awaitable[~.ShowEffectiveAutokeyConfigResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'show_effective_autokey_config' not in self._stubs: + self._stubs['show_effective_autokey_config'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.AutokeyAdmin/ShowEffectiveAutokeyConfig', + request_serializer=autokey_admin.ShowEffectiveAutokeyConfigRequest.serialize, + response_deserializer=autokey_admin.ShowEffectiveAutokeyConfigResponse.deserialize, + ) + return self._stubs['show_effective_autokey_config'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.update_autokey_config: self._wrap_method( + self.update_autokey_config, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_autokey_config: self._wrap_method( + self.get_autokey_config, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.show_effective_autokey_config: self._wrap_method( + self.show_effective_autokey_config, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @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_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ( + 'AutokeyAdminGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest.py new file mode 100644 index 000000000000..49a8d4f9fbe2 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest.py @@ -0,0 +1,1077 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from google.auth.transport.requests import AuthorizedSession # type: ignore +import json # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.kms_v1.types import autokey_admin +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseAutokeyAdminRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class AutokeyAdminRestInterceptor: + """Interceptor for AutokeyAdmin. + + 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 AutokeyAdminRestTransport. + + .. code-block:: python + class MyCustomAutokeyAdminInterceptor(AutokeyAdminRestInterceptor): + def pre_get_autokey_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_autokey_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_show_effective_autokey_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_show_effective_autokey_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_autokey_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_autokey_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AutokeyAdminRestTransport(interceptor=MyCustomAutokeyAdminInterceptor()) + client = AutokeyAdminClient(transport=transport) + + + """ + def pre_get_autokey_config(self, request: autokey_admin.GetAutokeyConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey_admin.GetAutokeyConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_autokey_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutokeyAdmin server. + """ + return request, metadata + + def post_get_autokey_config(self, response: autokey_admin.AutokeyConfig) -> autokey_admin.AutokeyConfig: + """Post-rpc interceptor for get_autokey_config + + Override in a subclass to manipulate the response + after it is returned by the AutokeyAdmin server but before + it is returned to user code. + """ + return response + + def pre_show_effective_autokey_config(self, request: autokey_admin.ShowEffectiveAutokeyConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey_admin.ShowEffectiveAutokeyConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for show_effective_autokey_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutokeyAdmin server. + """ + return request, metadata + + def post_show_effective_autokey_config(self, response: autokey_admin.ShowEffectiveAutokeyConfigResponse) -> autokey_admin.ShowEffectiveAutokeyConfigResponse: + """Post-rpc interceptor for show_effective_autokey_config + + Override in a subclass to manipulate the response + after it is returned by the AutokeyAdmin server but before + it is returned to user code. + """ + return response + + def pre_update_autokey_config(self, request: autokey_admin.UpdateAutokeyConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey_admin.UpdateAutokeyConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_autokey_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutokeyAdmin server. + """ + return request, metadata + + def post_update_autokey_config(self, response: autokey_admin.AutokeyConfig) -> autokey_admin.AutokeyConfig: + """Post-rpc interceptor for update_autokey_config + + Override in a subclass to manipulate the response + after it is returned by the AutokeyAdmin server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutokeyAdmin server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the AutokeyAdmin server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutokeyAdmin server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the AutokeyAdmin server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutokeyAdmin server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the AutokeyAdmin server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutokeyAdmin server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the AutokeyAdmin server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the AutokeyAdmin server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the AutokeyAdmin 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 AutokeyAdmin 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 AutokeyAdmin server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AutokeyAdminRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AutokeyAdminRestInterceptor + + +class AutokeyAdminRestTransport(_BaseAutokeyAdminRestTransport): + """REST backend synchronous transport for AutokeyAdmin. + + Provides interfaces for managing `Cloud KMS + Autokey `__ folder-level + configurations. A configuration is inherited by all descendent + projects. A configuration at one folder overrides any other + configurations in its ancestry. Setting a configuration on a folder + is a prerequisite for Cloud KMS Autokey, so that users working in a + descendant project can request provisioned + [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer + Managed Encryption Key (CMEK) use, on-demand. + + 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 = 'cloudkms.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[AutokeyAdminRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or AutokeyAdminRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetAutokeyConfig(_BaseAutokeyAdminRestTransport._BaseGetAutokeyConfig, AutokeyAdminRestStub): + def __hash__(self): + return hash("AutokeyAdminRestTransport.GetAutokeyConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: autokey_admin.GetAutokeyConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> autokey_admin.AutokeyConfig: + r"""Call the get autokey config method over HTTP. + + Args: + request (~.autokey_admin.GetAutokeyConfigRequest): + The request object. Request message for + [GetAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.autokey_admin.AutokeyConfig: + Cloud KMS Autokey configuration for a + folder. + + """ + + http_options = _BaseAutokeyAdminRestTransport._BaseGetAutokeyConfig._get_http_options() + request, metadata = self._interceptor.pre_get_autokey_config(request, metadata) + transcoded_request = _BaseAutokeyAdminRestTransport._BaseGetAutokeyConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyAdminRestTransport._BaseGetAutokeyConfig._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyAdminRestTransport._GetAutokeyConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = autokey_admin.AutokeyConfig() + pb_resp = autokey_admin.AutokeyConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_autokey_config(resp) + return resp + + class _ShowEffectiveAutokeyConfig(_BaseAutokeyAdminRestTransport._BaseShowEffectiveAutokeyConfig, AutokeyAdminRestStub): + def __hash__(self): + return hash("AutokeyAdminRestTransport.ShowEffectiveAutokeyConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: autokey_admin.ShowEffectiveAutokeyConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> autokey_admin.ShowEffectiveAutokeyConfigResponse: + r"""Call the show effective autokey + config method over HTTP. + + Args: + request (~.autokey_admin.ShowEffectiveAutokeyConfigRequest): + The request object. Request message for + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.autokey_admin.ShowEffectiveAutokeyConfigResponse: + Response message for + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + + """ + + http_options = _BaseAutokeyAdminRestTransport._BaseShowEffectiveAutokeyConfig._get_http_options() + request, metadata = self._interceptor.pre_show_effective_autokey_config(request, metadata) + transcoded_request = _BaseAutokeyAdminRestTransport._BaseShowEffectiveAutokeyConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyAdminRestTransport._BaseShowEffectiveAutokeyConfig._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyAdminRestTransport._ShowEffectiveAutokeyConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = autokey_admin.ShowEffectiveAutokeyConfigResponse() + pb_resp = autokey_admin.ShowEffectiveAutokeyConfigResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_show_effective_autokey_config(resp) + return resp + + class _UpdateAutokeyConfig(_BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig, AutokeyAdminRestStub): + def __hash__(self): + return hash("AutokeyAdminRestTransport.UpdateAutokeyConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: autokey_admin.UpdateAutokeyConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> autokey_admin.AutokeyConfig: + r"""Call the update autokey config method over HTTP. + + Args: + request (~.autokey_admin.UpdateAutokeyConfigRequest): + The request object. Request message for + [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.autokey_admin.AutokeyConfig: + Cloud KMS Autokey configuration for a + folder. + + """ + + http_options = _BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig._get_http_options() + request, metadata = self._interceptor.pre_update_autokey_config(request, metadata) + transcoded_request = _BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig._get_transcoded_request(http_options, request) + + body = _BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyAdminRestTransport._UpdateAutokeyConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = autokey_admin.AutokeyConfig() + pb_resp = autokey_admin.AutokeyConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_autokey_config(resp) + return resp + + @property + def get_autokey_config(self) -> Callable[ + [autokey_admin.GetAutokeyConfigRequest], + autokey_admin.AutokeyConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetAutokeyConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def show_effective_autokey_config(self) -> Callable[ + [autokey_admin.ShowEffectiveAutokeyConfigRequest], + autokey_admin.ShowEffectiveAutokeyConfigResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ShowEffectiveAutokeyConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_autokey_config(self) -> Callable[ + [autokey_admin.UpdateAutokeyConfigRequest], + autokey_admin.AutokeyConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateAutokeyConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseAutokeyAdminRestTransport._BaseGetLocation, AutokeyAdminRestStub): + def __hash__(self): + return hash("AutokeyAdminRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseAutokeyAdminRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseAutokeyAdminRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyAdminRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyAdminRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseAutokeyAdminRestTransport._BaseListLocations, AutokeyAdminRestStub): + def __hash__(self): + return hash("AutokeyAdminRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseAutokeyAdminRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseAutokeyAdminRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyAdminRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyAdminRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseAutokeyAdminRestTransport._BaseGetIamPolicy, AutokeyAdminRestStub): + def __hash__(self): + return hash("AutokeyAdminRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseAutokeyAdminRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseAutokeyAdminRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyAdminRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyAdminRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseAutokeyAdminRestTransport._BaseSetIamPolicy, AutokeyAdminRestStub): + def __hash__(self): + return hash("AutokeyAdminRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseAutokeyAdminRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseAutokeyAdminRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseAutokeyAdminRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAutokeyAdminRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyAdminRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseAutokeyAdminRestTransport._BaseTestIamPermissions, AutokeyAdminRestStub): + def __hash__(self): + return hash("AutokeyAdminRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseAutokeyAdminRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseAutokeyAdminRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseAutokeyAdminRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseAutokeyAdminRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyAdminRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseAutokeyAdminRestTransport._BaseGetOperation, AutokeyAdminRestStub): + def __hash__(self): + return hash("AutokeyAdminRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, 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 = _BaseAutokeyAdminRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseAutokeyAdminRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseAutokeyAdminRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + # Send the request + response = AutokeyAdminRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'AutokeyAdminRestTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest_base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest_base.py new file mode 100644 index 000000000000..dfa81a11c0c4 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest_base.py @@ -0,0 +1,434 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import AutokeyAdminTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.kms_v1.types import autokey_admin +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseAutokeyAdminRestTransport(AutokeyAdminTransport): + """Base REST backend transport for AutokeyAdmin. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'cloudkms.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseGetAutokeyConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=folders/*/autokeyConfig}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = autokey_admin.GetAutokeyConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAutokeyAdminRestTransport._BaseGetAutokeyConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseShowEffectiveAutokeyConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*}:showEffectiveAutokeyConfig', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = autokey_admin.ShowEffectiveAutokeyConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAutokeyAdminRestTransport._BaseShowEffectiveAutokeyConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateAutokeyConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{autokey_config.name=folders/*/autokeyConfig}', + 'body': 'autokey_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = autokey_admin.UpdateAutokeyConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:getIamPolicy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseAutokeyAdminRestTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/__init__.py new file mode 100644 index 000000000000..b284cc950ea1 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import EkmServiceClient +from .async_client import EkmServiceAsyncClient + +__all__ = ( + 'EkmServiceClient', + 'EkmServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/async_client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/async_client.py new file mode 100644 index 000000000000..064a8079440d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/async_client.py @@ -0,0 +1,1526 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.kms_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.kms_v1.services.ekm_service import pagers +from google.cloud.kms_v1.types import ekm_service +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EkmServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import EkmServiceGrpcAsyncIOTransport +from .client import EkmServiceClient + + +class EkmServiceAsyncClient: + """Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + """ + + _client: EkmServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = EkmServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = EkmServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = EkmServiceClient._DEFAULT_UNIVERSE + + ekm_config_path = staticmethod(EkmServiceClient.ekm_config_path) + parse_ekm_config_path = staticmethod(EkmServiceClient.parse_ekm_config_path) + ekm_connection_path = staticmethod(EkmServiceClient.ekm_connection_path) + parse_ekm_connection_path = staticmethod(EkmServiceClient.parse_ekm_connection_path) + service_path = staticmethod(EkmServiceClient.service_path) + parse_service_path = staticmethod(EkmServiceClient.parse_service_path) + common_billing_account_path = staticmethod(EkmServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(EkmServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(EkmServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(EkmServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(EkmServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(EkmServiceClient.parse_common_organization_path) + common_project_path = staticmethod(EkmServiceClient.common_project_path) + parse_common_project_path = staticmethod(EkmServiceClient.parse_common_project_path) + common_location_path = staticmethod(EkmServiceClient.common_location_path) + parse_common_location_path = staticmethod(EkmServiceClient.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: + EkmServiceAsyncClient: The constructed client. + """ + return EkmServiceClient.from_service_account_info.__func__(EkmServiceAsyncClient, 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: + EkmServiceAsyncClient: The constructed client. + """ + return EkmServiceClient.from_service_account_file.__func__(EkmServiceAsyncClient, 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 EkmServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> EkmServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EkmServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = EkmServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, EkmServiceTransport, Callable[..., EkmServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the ekm service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,EkmServiceTransport,Callable[..., EkmServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the EkmServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = EkmServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_ekm_connections(self, + request: Optional[Union[ekm_service.ListEkmConnectionsRequest, 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.ListEkmConnectionsAsyncPager: + r"""Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_list_ekm_connections(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListEkmConnectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_ekm_connections(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ListEkmConnectionsRequest, dict]]): + The request object. Request message for + [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. + parent (:class:`str`): + Required. The resource name of the location associated + with the + [EkmConnections][google.cloud.kms.v1.EkmConnection] to + list, in the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.services.ekm_service.pagers.ListEkmConnectionsAsyncPager: + Response message for + [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.ListEkmConnectionsRequest): + request = ekm_service.ListEkmConnectionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_ekm_connections] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEkmConnectionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_ekm_connection(self, + request: Optional[Union[ekm_service.GetEkmConnectionRequest, 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]] = (), + ) -> ekm_service.EkmConnection: + r"""Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_get_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetEkmConnectionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_ekm_connection(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GetEkmConnectionRequest, dict]]): + The request object. Request message for + [EkmService.GetEkmConnection][google.cloud.kms.v1.EkmService.GetEkmConnection]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.EkmConnection.name] of the + [EkmConnection][google.cloud.kms.v1.EkmConnection] to + get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.GetEkmConnectionRequest): + request = ekm_service.GetEkmConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_ekm_connection(self, + request: Optional[Union[ekm_service.CreateEkmConnectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + ekm_connection_id: Optional[str] = None, + ekm_connection: Optional[ekm_service.EkmConnection] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_create_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.CreateEkmConnectionRequest( + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ) + + # Make the request + response = await client.create_ekm_connection(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.CreateEkmConnectionRequest, dict]]): + The request object. Request message for + [EkmService.CreateEkmConnection][google.cloud.kms.v1.EkmService.CreateEkmConnection]. + parent (:class:`str`): + Required. The resource name of the location associated + with the + [EkmConnection][google.cloud.kms.v1.EkmConnection], in + the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection_id (:class:`str`): + Required. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}``. + + This corresponds to the ``ekm_connection_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection (:class:`google.cloud.kms_v1.types.EkmConnection`): + Required. An + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + initial field values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, ekm_connection_id, ekm_connection]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.CreateEkmConnectionRequest): + request = ekm_service.CreateEkmConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if ekm_connection_id is not None: + request.ekm_connection_id = ekm_connection_id + if ekm_connection is not None: + request.ekm_connection = ekm_connection + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_ekm_connection(self, + request: Optional[Union[ekm_service.UpdateEkmConnectionRequest, dict]] = None, + *, + ekm_connection: Optional[ekm_service.EkmConnection] = 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]] = (), + ) -> ekm_service.EkmConnection: + r"""Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_update_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateEkmConnectionRequest( + ) + + # Make the request + response = await client.update_ekm_connection(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.UpdateEkmConnectionRequest, dict]]): + The request object. Request message for + [EkmService.UpdateEkmConnection][google.cloud.kms.v1.EkmService.UpdateEkmConnection]. + ekm_connection (:class:`google.cloud.kms_v1.types.EkmConnection`): + Required. + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + updated values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([ekm_connection, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.UpdateEkmConnectionRequest): + request = ekm_service.UpdateEkmConnectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if ekm_connection is not None: + request.ekm_connection = ekm_connection + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("ekm_connection.name", request.ekm_connection.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_ekm_config(self, + request: Optional[Union[ekm_service.GetEkmConfigRequest, 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]] = (), + ) -> ekm_service.EkmConfig: + r"""Returns the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton + resource for a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_get_ekm_config(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetEkmConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_ekm_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GetEkmConfigRequest, dict]]): + The request object. Request message for + [EkmService.GetEkmConfig][google.cloud.kms.v1.EkmService.GetEkmConfig]. + name (:class:`str`): + Required. The [name][google.cloud.kms.v1.EkmConfig.name] + of the [EkmConfig][google.cloud.kms.v1.EkmConfig] to + get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConfig: + An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a singleton resource that + represents configuration parameters that apply to all + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] + in a given project and location. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.GetEkmConfigRequest): + request = ekm_service.GetEkmConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_ekm_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_ekm_config(self, + request: Optional[Union[ekm_service.UpdateEkmConfigRequest, dict]] = None, + *, + ekm_config: Optional[ekm_service.EkmConfig] = 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]] = (), + ) -> ekm_service.EkmConfig: + r"""Updates the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton + resource for a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_update_ekm_config(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateEkmConfigRequest( + ) + + # Make the request + response = await client.update_ekm_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.UpdateEkmConfigRequest, dict]]): + The request object. Request message for + [EkmService.UpdateEkmConfig][google.cloud.kms.v1.EkmService.UpdateEkmConfig]. + ekm_config (:class:`google.cloud.kms_v1.types.EkmConfig`): + Required. [EkmConfig][google.cloud.kms.v1.EkmConfig] + with updated values. + + This corresponds to the ``ekm_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConfig: + An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a singleton resource that + represents configuration parameters that apply to all + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] + in a given project and location. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([ekm_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.UpdateEkmConfigRequest): + request = ekm_service.UpdateEkmConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if ekm_config is not None: + request.ekm_config = ekm_config + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_ekm_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("ekm_config.name", request.ekm_config.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def verify_connectivity(self, + request: Optional[Union[ekm_service.VerifyConnectivityRequest, 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]] = (), + ) -> ekm_service.VerifyConnectivityResponse: + r"""Verifies that Cloud KMS can successfully connect to the external + key manager specified by an + [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is + an error connecting to the EKM, this method returns a + FAILED_PRECONDITION status containing structured information as + described at + https://cloud.google.com/kms/docs/reference/ekm_errors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_verify_connectivity(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.VerifyConnectivityRequest( + name="name_value", + ) + + # Make the request + response = await client.verify_connectivity(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.VerifyConnectivityRequest, dict]]): + The request object. Request message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.EkmConnection.name] of the + [EkmConnection][google.cloud.kms.v1.EkmConnection] to + verify. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.VerifyConnectivityResponse: + Response message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.VerifyConnectivityRequest): + request = ekm_service.VerifyConnectivityRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.verify_connectivity] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does + not have a policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified permissions against the IAM access control + policy for a function. + + If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~iam_policy_pb2.PolicyTestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "EkmServiceAsyncClient": + 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__ = ( + "EkmServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/client.py new file mode 100644 index 000000000000..7a7821335cd4 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/client.py @@ -0,0 +1,1880 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.kms_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.cloud.kms_v1.services.ekm_service import pagers +from google.cloud.kms_v1.types import ekm_service +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from .transports.base import EkmServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import EkmServiceGrpcTransport +from .transports.grpc_asyncio import EkmServiceGrpcAsyncIOTransport +from .transports.rest import EkmServiceRestTransport + + +class EkmServiceClientMeta(type): + """Metaclass for the EkmService 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[EkmServiceTransport]] + _transport_registry["grpc"] = EkmServiceGrpcTransport + _transport_registry["grpc_asyncio"] = EkmServiceGrpcAsyncIOTransport + _transport_registry["rest"] = EkmServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[EkmServiceTransport]: + """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 EkmServiceClient(metaclass=EkmServiceClientMeta): + """Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "cloudkms.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudkms.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + EkmServiceClient: 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: + EkmServiceClient: 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) -> EkmServiceTransport: + """Returns the transport used by the client instance. + + Returns: + EkmServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def ekm_config_path(project: str,location: str,) -> str: + """Returns a fully-qualified ekm_config string.""" + return "projects/{project}/locations/{location}/ekmConfig".format(project=project, location=location, ) + + @staticmethod + def parse_ekm_config_path(path: str) -> Dict[str,str]: + """Parses a ekm_config path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/ekmConfig$", path) + return m.groupdict() if m else {} + + @staticmethod + def ekm_connection_path(project: str,location: str,ekm_connection: str,) -> str: + """Returns a fully-qualified ekm_connection string.""" + return "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format(project=project, location=location, ekm_connection=ekm_connection, ) + + @staticmethod + def parse_ekm_connection_path(path: str) -> Dict[str,str]: + """Parses a ekm_connection path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/ekmConnections/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str,location: str,namespace: str,service: str,) -> str: + """Returns a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str,str]: + """Parses a service path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = EkmServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = EkmServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = EkmServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, EkmServiceTransport, Callable[..., EkmServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the ekm service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,EkmServiceTransport,Callable[..., EkmServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the EkmServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = EkmServiceClient._read_environment_variables() + self._client_cert_source = EkmServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = EkmServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, EkmServiceTransport) + if transport_provided: + # transport is a EkmServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(EkmServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + EkmServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[EkmServiceTransport], Callable[..., EkmServiceTransport]] = ( + EkmServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., EkmServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_ekm_connections(self, + request: Optional[Union[ekm_service.ListEkmConnectionsRequest, 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.ListEkmConnectionsPager: + r"""Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_list_ekm_connections(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.ListEkmConnectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_ekm_connections(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ListEkmConnectionsRequest, dict]): + The request object. Request message for + [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. + parent (str): + Required. The resource name of the location associated + with the + [EkmConnections][google.cloud.kms.v1.EkmConnection] to + list, in the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.services.ekm_service.pagers.ListEkmConnectionsPager: + Response message for + [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.ListEkmConnectionsRequest): + request = ekm_service.ListEkmConnectionsRequest(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_ekm_connections] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEkmConnectionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_ekm_connection(self, + request: Optional[Union[ekm_service.GetEkmConnectionRequest, 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]] = (), + ) -> ekm_service.EkmConnection: + r"""Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_get_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetEkmConnectionRequest( + name="name_value", + ) + + # Make the request + response = client.get_ekm_connection(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GetEkmConnectionRequest, dict]): + The request object. Request message for + [EkmService.GetEkmConnection][google.cloud.kms.v1.EkmService.GetEkmConnection]. + name (str): + Required. The + [name][google.cloud.kms.v1.EkmConnection.name] of the + [EkmConnection][google.cloud.kms.v1.EkmConnection] to + get. + + 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.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.GetEkmConnectionRequest): + request = ekm_service.GetEkmConnectionRequest(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_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_ekm_connection(self, + request: Optional[Union[ekm_service.CreateEkmConnectionRequest, dict]] = None, + *, + parent: Optional[str] = None, + ekm_connection_id: Optional[str] = None, + ekm_connection: Optional[ekm_service.EkmConnection] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> ekm_service.EkmConnection: + r"""Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_create_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.CreateEkmConnectionRequest( + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ) + + # Make the request + response = client.create_ekm_connection(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.CreateEkmConnectionRequest, dict]): + The request object. Request message for + [EkmService.CreateEkmConnection][google.cloud.kms.v1.EkmService.CreateEkmConnection]. + parent (str): + Required. The resource name of the location associated + with the + [EkmConnection][google.cloud.kms.v1.EkmConnection], in + the format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection_id (str): + Required. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}``. + + This corresponds to the ``ekm_connection_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. An + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + initial field values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, ekm_connection_id, ekm_connection]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.CreateEkmConnectionRequest): + request = ekm_service.CreateEkmConnectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if ekm_connection_id is not None: + request.ekm_connection_id = ekm_connection_id + if ekm_connection is not None: + request.ekm_connection = ekm_connection + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_ekm_connection(self, + request: Optional[Union[ekm_service.UpdateEkmConnectionRequest, dict]] = None, + *, + ekm_connection: Optional[ekm_service.EkmConnection] = 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]] = (), + ) -> ekm_service.EkmConnection: + r"""Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_update_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.UpdateEkmConnectionRequest( + ) + + # Make the request + response = client.update_ekm_connection(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.UpdateEkmConnectionRequest, dict]): + The request object. Request message for + [EkmService.UpdateEkmConnection][google.cloud.kms.v1.EkmService.UpdateEkmConnection]. + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + updated values. + + This corresponds to the ``ekm_connection`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + 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.cloud.kms_v1.types.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for + creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([ekm_connection, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.UpdateEkmConnectionRequest): + request = ekm_service.UpdateEkmConnectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if ekm_connection is not None: + request.ekm_connection = ekm_connection + 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_ekm_connection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("ekm_connection.name", request.ekm_connection.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_ekm_config(self, + request: Optional[Union[ekm_service.GetEkmConfigRequest, 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]] = (), + ) -> ekm_service.EkmConfig: + r"""Returns the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton + resource for a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_get_ekm_config(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetEkmConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_ekm_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GetEkmConfigRequest, dict]): + The request object. Request message for + [EkmService.GetEkmConfig][google.cloud.kms.v1.EkmService.GetEkmConfig]. + name (str): + Required. The [name][google.cloud.kms.v1.EkmConfig.name] + of the [EkmConfig][google.cloud.kms.v1.EkmConfig] to + get. + + 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.kms_v1.types.EkmConfig: + An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a singleton resource that + represents configuration parameters that apply to all + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] + in a given project and location. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.GetEkmConfigRequest): + request = ekm_service.GetEkmConfigRequest(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_ekm_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_ekm_config(self, + request: Optional[Union[ekm_service.UpdateEkmConfigRequest, dict]] = None, + *, + ekm_config: Optional[ekm_service.EkmConfig] = 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]] = (), + ) -> ekm_service.EkmConfig: + r"""Updates the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton + resource for a given project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_update_ekm_config(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.UpdateEkmConfigRequest( + ) + + # Make the request + response = client.update_ekm_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.UpdateEkmConfigRequest, dict]): + The request object. Request message for + [EkmService.UpdateEkmConfig][google.cloud.kms.v1.EkmService.UpdateEkmConfig]. + ekm_config (google.cloud.kms_v1.types.EkmConfig): + Required. [EkmConfig][google.cloud.kms.v1.EkmConfig] + with updated values. + + This corresponds to the ``ekm_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + 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.cloud.kms_v1.types.EkmConfig: + An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a singleton resource that + represents configuration parameters that apply to all + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] + in a given project and location. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([ekm_config, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.UpdateEkmConfigRequest): + request = ekm_service.UpdateEkmConfigRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if ekm_config is not None: + request.ekm_config = ekm_config + 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_ekm_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("ekm_config.name", request.ekm_config.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def verify_connectivity(self, + request: Optional[Union[ekm_service.VerifyConnectivityRequest, 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]] = (), + ) -> ekm_service.VerifyConnectivityResponse: + r"""Verifies that Cloud KMS can successfully connect to the external + key manager specified by an + [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is + an error connecting to the EKM, this method returns a + FAILED_PRECONDITION status containing structured information as + described at + https://cloud.google.com/kms/docs/reference/ekm_errors. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_verify_connectivity(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.VerifyConnectivityRequest( + name="name_value", + ) + + # Make the request + response = client.verify_connectivity(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.VerifyConnectivityRequest, dict]): + The request object. Request message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + name (str): + Required. The + [name][google.cloud.kms.v1.EkmConnection.name] of the + [EkmConnection][google.cloud.kms.v1.EkmConnection] to + verify. + + 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.kms_v1.types.VerifyConnectivityResponse: + Response message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, ekm_service.VerifyConnectivityRequest): + request = ekm_service.VerifyConnectivityRequest(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.verify_connectivity] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "EkmServiceClient": + 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 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 = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "EkmServiceClient", +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/pagers.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/pagers.py new file mode 100644 index 000000000000..43533cb1df06 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/pagers.py @@ -0,0 +1,162 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.kms_v1.types import ekm_service + + +class ListEkmConnectionsPager: + """A pager for iterating through ``list_ekm_connections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``ekm_connections`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEkmConnections`` requests and continue to iterate + through the ``ekm_connections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` + 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[..., ekm_service.ListEkmConnectionsResponse], + request: ekm_service.ListEkmConnectionsRequest, + response: ekm_service.ListEkmConnectionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListEkmConnectionsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListEkmConnectionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = ekm_service.ListEkmConnectionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[ekm_service.ListEkmConnectionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[ekm_service.EkmConnection]: + for page in self.pages: + yield from page.ekm_connections + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListEkmConnectionsAsyncPager: + """A pager for iterating through ``list_ekm_connections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``ekm_connections`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEkmConnections`` requests and continue to iterate + through the ``ekm_connections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` + 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[ekm_service.ListEkmConnectionsResponse]], + request: ekm_service.ListEkmConnectionsRequest, + response: ekm_service.ListEkmConnectionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListEkmConnectionsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListEkmConnectionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = ekm_service.ListEkmConnectionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[ekm_service.ListEkmConnectionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[ekm_service.EkmConnection]: + async def async_generator(): + async for page in self.pages: + for response in page.ekm_connections: + 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-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/README.rst b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/README.rst new file mode 100644 index 000000000000..c0fa99e1eca8 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`EkmServiceTransport` is the ABC for all transports. +- public child `EkmServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `EkmServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseEkmServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `EkmServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py new file mode 100644 index 000000000000..65f4d6f3c851 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import EkmServiceTransport +from .grpc import EkmServiceGrpcTransport +from .grpc_asyncio import EkmServiceGrpcAsyncIOTransport +from .rest import EkmServiceRestTransport +from .rest import EkmServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[EkmServiceTransport]] +_transport_registry['grpc'] = EkmServiceGrpcTransport +_transport_registry['grpc_asyncio'] = EkmServiceGrpcAsyncIOTransport +_transport_registry['rest'] = EkmServiceRestTransport + +__all__ = ( + 'EkmServiceTransport', + 'EkmServiceGrpcTransport', + 'EkmServiceGrpcAsyncIOTransport', + 'EkmServiceRestTransport', + 'EkmServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py new file mode 100644 index 000000000000..6b029761cb3f --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py @@ -0,0 +1,368 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.kms_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.kms_v1.types import ekm_service +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class EkmServiceTransport(abc.ABC): + """Abstract transport class for EkmService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', + ) + + DEFAULT_HOST: str = 'cloudkms.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_ekm_connections: gapic_v1.method.wrap_method( + self.list_ekm_connections, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_ekm_connection: gapic_v1.method.wrap_method( + self.get_ekm_connection, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_ekm_connection: gapic_v1.method.wrap_method( + self.create_ekm_connection, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_ekm_connection: gapic_v1.method.wrap_method( + self.update_ekm_connection, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_ekm_config: gapic_v1.method.wrap_method( + self.get_ekm_config, + default_timeout=None, + client_info=client_info, + ), + self.update_ekm_config: gapic_v1.method.wrap_method( + self.update_ekm_config, + default_timeout=None, + client_info=client_info, + ), + self.verify_connectivity: gapic_v1.method.wrap_method( + self.verify_connectivity, + default_timeout=None, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + 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_ekm_connections(self) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], + Union[ + ekm_service.ListEkmConnectionsResponse, + Awaitable[ekm_service.ListEkmConnectionsResponse] + ]]: + raise NotImplementedError() + + @property + def get_ekm_connection(self) -> Callable[ + [ekm_service.GetEkmConnectionRequest], + Union[ + ekm_service.EkmConnection, + Awaitable[ekm_service.EkmConnection] + ]]: + raise NotImplementedError() + + @property + def create_ekm_connection(self) -> Callable[ + [ekm_service.CreateEkmConnectionRequest], + Union[ + ekm_service.EkmConnection, + Awaitable[ekm_service.EkmConnection] + ]]: + raise NotImplementedError() + + @property + def update_ekm_connection(self) -> Callable[ + [ekm_service.UpdateEkmConnectionRequest], + Union[ + ekm_service.EkmConnection, + Awaitable[ekm_service.EkmConnection] + ]]: + raise NotImplementedError() + + @property + def get_ekm_config(self) -> Callable[ + [ekm_service.GetEkmConfigRequest], + Union[ + ekm_service.EkmConfig, + Awaitable[ekm_service.EkmConfig] + ]]: + raise NotImplementedError() + + @property + def update_ekm_config(self) -> Callable[ + [ekm_service.UpdateEkmConfigRequest], + Union[ + ekm_service.EkmConfig, + Awaitable[ekm_service.EkmConfig] + ]]: + raise NotImplementedError() + + @property + def verify_connectivity(self) -> Callable[ + [ekm_service.VerifyConnectivityRequest], + Union[ + ekm_service.VerifyConnectivityResponse, + Awaitable[ekm_service.VerifyConnectivityResponse] + ]]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'EkmServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py new file mode 100644 index 000000000000..b41fc92314e1 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py @@ -0,0 +1,579 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.kms_v1.types import ekm_service +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import EkmServiceTransport, DEFAULT_CLIENT_INFO + + +class EkmServiceGrpcTransport(EkmServiceTransport): + """gRPC backend transport for EkmService. + + Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + + 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 = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudkms.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_ekm_connections(self) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], + ekm_service.ListEkmConnectionsResponse]: + r"""Return a callable for the list ekm connections method over gRPC. + + Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.ListEkmConnectionsRequest], + ~.ListEkmConnectionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_connections' not in self._stubs: + self._stubs['list_ekm_connections'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/ListEkmConnections', + request_serializer=ekm_service.ListEkmConnectionsRequest.serialize, + response_deserializer=ekm_service.ListEkmConnectionsResponse.deserialize, + ) + return self._stubs['list_ekm_connections'] + + @property + def get_ekm_connection(self) -> Callable[ + [ekm_service.GetEkmConnectionRequest], + ekm_service.EkmConnection]: + r"""Return a callable for the get ekm connection method over gRPC. + + Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.GetEkmConnectionRequest], + ~.EkmConnection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: + self._stubs['get_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/GetEkmConnection', + request_serializer=ekm_service.GetEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['get_ekm_connection'] + + @property + def create_ekm_connection(self) -> Callable[ + [ekm_service.CreateEkmConnectionRequest], + ekm_service.EkmConnection]: + r"""Return a callable for the create ekm connection method over gRPC. + + Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + Returns: + Callable[[~.CreateEkmConnectionRequest], + ~.EkmConnection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: + self._stubs['create_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/CreateEkmConnection', + request_serializer=ekm_service.CreateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['create_ekm_connection'] + + @property + def update_ekm_connection(self) -> Callable[ + [ekm_service.UpdateEkmConnectionRequest], + ekm_service.EkmConnection]: + r"""Return a callable for the update ekm connection method over gRPC. + + Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + Returns: + Callable[[~.UpdateEkmConnectionRequest], + ~.EkmConnection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: + self._stubs['update_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/UpdateEkmConnection', + request_serializer=ekm_service.UpdateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['update_ekm_connection'] + + @property + def get_ekm_config(self) -> Callable[ + [ekm_service.GetEkmConfigRequest], + ekm_service.EkmConfig]: + r"""Return a callable for the get ekm config method over gRPC. + + Returns the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton + resource for a given project and location. + + Returns: + Callable[[~.GetEkmConfigRequest], + ~.EkmConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_config' not in self._stubs: + self._stubs['get_ekm_config'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/GetEkmConfig', + request_serializer=ekm_service.GetEkmConfigRequest.serialize, + response_deserializer=ekm_service.EkmConfig.deserialize, + ) + return self._stubs['get_ekm_config'] + + @property + def update_ekm_config(self) -> Callable[ + [ekm_service.UpdateEkmConfigRequest], + ekm_service.EkmConfig]: + r"""Return a callable for the update ekm config method over gRPC. + + Updates the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton + resource for a given project and location. + + Returns: + Callable[[~.UpdateEkmConfigRequest], + ~.EkmConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_config' not in self._stubs: + self._stubs['update_ekm_config'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/UpdateEkmConfig', + request_serializer=ekm_service.UpdateEkmConfigRequest.serialize, + response_deserializer=ekm_service.EkmConfig.deserialize, + ) + return self._stubs['update_ekm_config'] + + @property + def verify_connectivity(self) -> Callable[ + [ekm_service.VerifyConnectivityRequest], + ekm_service.VerifyConnectivityResponse]: + r"""Return a callable for the verify connectivity method over gRPC. + + Verifies that Cloud KMS can successfully connect to the external + key manager specified by an + [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is + an error connecting to the EKM, this method returns a + FAILED_PRECONDITION status containing structured information as + described at + https://cloud.google.com/kms/docs/reference/ekm_errors. + + Returns: + Callable[[~.VerifyConnectivityRequest], + ~.VerifyConnectivityResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'verify_connectivity' not in self._stubs: + self._stubs['verify_connectivity'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/VerifyConnectivity', + request_serializer=ekm_service.VerifyConnectivityRequest.serialize, + response_deserializer=ekm_service.VerifyConnectivityResponse.deserialize, + ) + return self._stubs['verify_connectivity'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def close(self): + self.grpc_channel.close() + + @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_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'EkmServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..c4e5842edf31 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py @@ -0,0 +1,701 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.kms_v1.types import ekm_service +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import EkmServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import EkmServiceGrpcTransport + + +class EkmServiceGrpcAsyncIOTransport(EkmServiceTransport): + """gRPC AsyncIO backend transport for EkmService. + + Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + + 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 = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_ekm_connections(self) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], + Awaitable[ekm_service.ListEkmConnectionsResponse]]: + r"""Return a callable for the list ekm connections method over gRPC. + + Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.ListEkmConnectionsRequest], + Awaitable[~.ListEkmConnectionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_connections' not in self._stubs: + self._stubs['list_ekm_connections'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/ListEkmConnections', + request_serializer=ekm_service.ListEkmConnectionsRequest.serialize, + response_deserializer=ekm_service.ListEkmConnectionsResponse.deserialize, + ) + return self._stubs['list_ekm_connections'] + + @property + def get_ekm_connection(self) -> Callable[ + [ekm_service.GetEkmConnectionRequest], + Awaitable[ekm_service.EkmConnection]]: + r"""Return a callable for the get ekm connection method over gRPC. + + Returns metadata for a given + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Returns: + Callable[[~.GetEkmConnectionRequest], + Awaitable[~.EkmConnection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: + self._stubs['get_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/GetEkmConnection', + request_serializer=ekm_service.GetEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['get_ekm_connection'] + + @property + def create_ekm_connection(self) -> Callable[ + [ekm_service.CreateEkmConnectionRequest], + Awaitable[ekm_service.EkmConnection]]: + r"""Return a callable for the create ekm connection method over gRPC. + + Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] + in a given Project and Location. + + Returns: + Callable[[~.CreateEkmConnectionRequest], + Awaitable[~.EkmConnection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: + self._stubs['create_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/CreateEkmConnection', + request_serializer=ekm_service.CreateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['create_ekm_connection'] + + @property + def update_ekm_connection(self) -> Callable[ + [ekm_service.UpdateEkmConnectionRequest], + Awaitable[ekm_service.EkmConnection]]: + r"""Return a callable for the update ekm connection method over gRPC. + + Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s + metadata. + + Returns: + Callable[[~.UpdateEkmConnectionRequest], + Awaitable[~.EkmConnection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: + self._stubs['update_ekm_connection'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/UpdateEkmConnection', + request_serializer=ekm_service.UpdateEkmConnectionRequest.serialize, + response_deserializer=ekm_service.EkmConnection.deserialize, + ) + return self._stubs['update_ekm_connection'] + + @property + def get_ekm_config(self) -> Callable[ + [ekm_service.GetEkmConfigRequest], + Awaitable[ekm_service.EkmConfig]]: + r"""Return a callable for the get ekm config method over gRPC. + + Returns the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton + resource for a given project and location. + + Returns: + Callable[[~.GetEkmConfigRequest], + Awaitable[~.EkmConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_config' not in self._stubs: + self._stubs['get_ekm_config'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/GetEkmConfig', + request_serializer=ekm_service.GetEkmConfigRequest.serialize, + response_deserializer=ekm_service.EkmConfig.deserialize, + ) + return self._stubs['get_ekm_config'] + + @property + def update_ekm_config(self) -> Callable[ + [ekm_service.UpdateEkmConfigRequest], + Awaitable[ekm_service.EkmConfig]]: + r"""Return a callable for the update ekm config method over gRPC. + + Updates the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton + resource for a given project and location. + + Returns: + Callable[[~.UpdateEkmConfigRequest], + Awaitable[~.EkmConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_ekm_config' not in self._stubs: + self._stubs['update_ekm_config'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/UpdateEkmConfig', + request_serializer=ekm_service.UpdateEkmConfigRequest.serialize, + response_deserializer=ekm_service.EkmConfig.deserialize, + ) + return self._stubs['update_ekm_config'] + + @property + def verify_connectivity(self) -> Callable[ + [ekm_service.VerifyConnectivityRequest], + Awaitable[ekm_service.VerifyConnectivityResponse]]: + r"""Return a callable for the verify connectivity method over gRPC. + + Verifies that Cloud KMS can successfully connect to the external + key manager specified by an + [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is + an error connecting to the EKM, this method returns a + FAILED_PRECONDITION status containing structured information as + described at + https://cloud.google.com/kms/docs/reference/ekm_errors. + + Returns: + Callable[[~.VerifyConnectivityRequest], + Awaitable[~.VerifyConnectivityResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'verify_connectivity' not in self._stubs: + self._stubs['verify_connectivity'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.EkmService/VerifyConnectivity', + request_serializer=ekm_service.VerifyConnectivityRequest.serialize, + response_deserializer=ekm_service.VerifyConnectivityResponse.deserialize, + ) + return self._stubs['verify_connectivity'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_ekm_connections: self._wrap_method( + self.list_ekm_connections, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_ekm_connection: self._wrap_method( + self.get_ekm_connection, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_ekm_connection: self._wrap_method( + self.create_ekm_connection, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_ekm_connection: self._wrap_method( + self.update_ekm_connection, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_ekm_config: self._wrap_method( + self.get_ekm_config, + default_timeout=None, + client_info=client_info, + ), + self.update_ekm_config: self._wrap_method( + self.update_ekm_config, + default_timeout=None, + client_info=client_info, + ), + self.verify_connectivity: self._wrap_method( + self.verify_connectivity, + default_timeout=None, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @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_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ( + 'EkmServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest.py new file mode 100644 index 000000000000..e25b8b0b7b0f --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest.py @@ -0,0 +1,1553 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseEkmServiceRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class EkmServiceRestInterceptor: + """Interceptor for EkmService. + + 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 EkmServiceRestTransport. + + .. code-block:: python + class MyCustomEkmServiceInterceptor(EkmServiceRestInterceptor): + def pre_create_ekm_connection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_ekm_connection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_ekm_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_ekm_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_ekm_connection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_ekm_connection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_ekm_connections(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_ekm_connections(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_ekm_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_ekm_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_ekm_connection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_ekm_connection(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_verify_connectivity(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_verify_connectivity(self, response): + logging.log(f"Received response: {response}") + return response + + transport = EkmServiceRestTransport(interceptor=MyCustomEkmServiceInterceptor()) + client = EkmServiceClient(transport=transport) + + + """ + def pre_create_ekm_connection(self, request: ekm_service.CreateEkmConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.CreateEkmConnectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_ekm_connection + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_create_ekm_connection(self, response: ekm_service.EkmConnection) -> ekm_service.EkmConnection: + """Post-rpc interceptor for create_ekm_connection + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_get_ekm_config(self, request: ekm_service.GetEkmConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.GetEkmConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_ekm_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_get_ekm_config(self, response: ekm_service.EkmConfig) -> ekm_service.EkmConfig: + """Post-rpc interceptor for get_ekm_config + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_get_ekm_connection(self, request: ekm_service.GetEkmConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.GetEkmConnectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_ekm_connection + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_get_ekm_connection(self, response: ekm_service.EkmConnection) -> ekm_service.EkmConnection: + """Post-rpc interceptor for get_ekm_connection + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_list_ekm_connections(self, request: ekm_service.ListEkmConnectionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.ListEkmConnectionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_ekm_connections + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_list_ekm_connections(self, response: ekm_service.ListEkmConnectionsResponse) -> ekm_service.ListEkmConnectionsResponse: + """Post-rpc interceptor for list_ekm_connections + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_update_ekm_config(self, request: ekm_service.UpdateEkmConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.UpdateEkmConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_ekm_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_update_ekm_config(self, response: ekm_service.EkmConfig) -> ekm_service.EkmConfig: + """Post-rpc interceptor for update_ekm_config + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_update_ekm_connection(self, request: ekm_service.UpdateEkmConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.UpdateEkmConnectionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_ekm_connection + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_update_ekm_connection(self, response: ekm_service.EkmConnection) -> ekm_service.EkmConnection: + """Post-rpc interceptor for update_ekm_connection + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_verify_connectivity(self, request: ekm_service.VerifyConnectivityRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.VerifyConnectivityRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for verify_connectivity + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_verify_connectivity(self, response: ekm_service.VerifyConnectivityResponse) -> ekm_service.VerifyConnectivityResponse: + """Post-rpc interceptor for verify_connectivity + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the EkmService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the EkmService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the EkmService 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 EkmService 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 EkmService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class EkmServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: EkmServiceRestInterceptor + + +class EkmServiceRestTransport(_BaseEkmServiceRestTransport): + """REST backend synchronous transport for EkmService. + + Google Cloud Key Management EKM Service + + Manages external cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [EkmConnection][google.cloud.kms.v1.EkmConnection] + + 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 = 'cloudkms.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[EkmServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or EkmServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateEkmConnection(_BaseEkmServiceRestTransport._BaseCreateEkmConnection, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.CreateEkmConnection") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: ekm_service.CreateEkmConnectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> ekm_service.EkmConnection: + r"""Call the create ekm connection method over HTTP. + + Args: + request (~.ekm_service.CreateEkmConnectionRequest): + The request object. Request message for + [EkmService.CreateEkmConnection][google.cloud.kms.v1.EkmService.CreateEkmConnection]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.ekm_service.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] + represents an individual EKM connection. It can be used + for creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + + http_options = _BaseEkmServiceRestTransport._BaseCreateEkmConnection._get_http_options() + request, metadata = self._interceptor.pre_create_ekm_connection(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseCreateEkmConnection._get_transcoded_request(http_options, request) + + body = _BaseEkmServiceRestTransport._BaseCreateEkmConnection._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseCreateEkmConnection._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._CreateEkmConnection._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ekm_service.EkmConnection() + pb_resp = ekm_service.EkmConnection.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_ekm_connection(resp) + return resp + + class _GetEkmConfig(_BaseEkmServiceRestTransport._BaseGetEkmConfig, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.GetEkmConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: ekm_service.GetEkmConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> ekm_service.EkmConfig: + r"""Call the get ekm config method over HTTP. + + Args: + request (~.ekm_service.GetEkmConfigRequest): + The request object. Request message for + [EkmService.GetEkmConfig][google.cloud.kms.v1.EkmService.GetEkmConfig]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.ekm_service.EkmConfig: + An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a + singleton resource that represents configuration + parameters that apply to all + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] + in a given project and location. + + """ + + http_options = _BaseEkmServiceRestTransport._BaseGetEkmConfig._get_http_options() + request, metadata = self._interceptor.pre_get_ekm_config(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseGetEkmConfig._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseGetEkmConfig._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._GetEkmConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ekm_service.EkmConfig() + pb_resp = ekm_service.EkmConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_ekm_config(resp) + return resp + + class _GetEkmConnection(_BaseEkmServiceRestTransport._BaseGetEkmConnection, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.GetEkmConnection") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: ekm_service.GetEkmConnectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> ekm_service.EkmConnection: + r"""Call the get ekm connection method over HTTP. + + Args: + request (~.ekm_service.GetEkmConnectionRequest): + The request object. Request message for + [EkmService.GetEkmConnection][google.cloud.kms.v1.EkmService.GetEkmConnection]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.ekm_service.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] + represents an individual EKM connection. It can be used + for creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + + http_options = _BaseEkmServiceRestTransport._BaseGetEkmConnection._get_http_options() + request, metadata = self._interceptor.pre_get_ekm_connection(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseGetEkmConnection._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseGetEkmConnection._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._GetEkmConnection._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ekm_service.EkmConnection() + pb_resp = ekm_service.EkmConnection.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_ekm_connection(resp) + return resp + + class _ListEkmConnections(_BaseEkmServiceRestTransport._BaseListEkmConnections, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.ListEkmConnections") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: ekm_service.ListEkmConnectionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> ekm_service.ListEkmConnectionsResponse: + r"""Call the list ekm connections method over HTTP. + + Args: + request (~.ekm_service.ListEkmConnectionsRequest): + The request object. Request message for + [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.ekm_service.ListEkmConnectionsResponse: + Response message for + [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. + + """ + + http_options = _BaseEkmServiceRestTransport._BaseListEkmConnections._get_http_options() + request, metadata = self._interceptor.pre_list_ekm_connections(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseListEkmConnections._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseListEkmConnections._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._ListEkmConnections._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ekm_service.ListEkmConnectionsResponse() + pb_resp = ekm_service.ListEkmConnectionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_ekm_connections(resp) + return resp + + class _UpdateEkmConfig(_BaseEkmServiceRestTransport._BaseUpdateEkmConfig, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.UpdateEkmConfig") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: ekm_service.UpdateEkmConfigRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> ekm_service.EkmConfig: + r"""Call the update ekm config method over HTTP. + + Args: + request (~.ekm_service.UpdateEkmConfigRequest): + The request object. Request message for + [EkmService.UpdateEkmConfig][google.cloud.kms.v1.EkmService.UpdateEkmConfig]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.ekm_service.EkmConfig: + An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a + singleton resource that represents configuration + parameters that apply to all + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] + in a given project and location. + + """ + + http_options = _BaseEkmServiceRestTransport._BaseUpdateEkmConfig._get_http_options() + request, metadata = self._interceptor.pre_update_ekm_config(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseUpdateEkmConfig._get_transcoded_request(http_options, request) + + body = _BaseEkmServiceRestTransport._BaseUpdateEkmConfig._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseUpdateEkmConfig._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._UpdateEkmConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ekm_service.EkmConfig() + pb_resp = ekm_service.EkmConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_ekm_config(resp) + return resp + + class _UpdateEkmConnection(_BaseEkmServiceRestTransport._BaseUpdateEkmConnection, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.UpdateEkmConnection") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: ekm_service.UpdateEkmConnectionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> ekm_service.EkmConnection: + r"""Call the update ekm connection method over HTTP. + + Args: + request (~.ekm_service.UpdateEkmConnectionRequest): + The request object. Request message for + [EkmService.UpdateEkmConnection][google.cloud.kms.v1.EkmService.UpdateEkmConnection]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.ekm_service.EkmConnection: + An [EkmConnection][google.cloud.kms.v1.EkmConnection] + represents an individual EKM connection. It can be used + for creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] + and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + as well as performing cryptographic operations using + keys created within the + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + """ + + http_options = _BaseEkmServiceRestTransport._BaseUpdateEkmConnection._get_http_options() + request, metadata = self._interceptor.pre_update_ekm_connection(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseUpdateEkmConnection._get_transcoded_request(http_options, request) + + body = _BaseEkmServiceRestTransport._BaseUpdateEkmConnection._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseUpdateEkmConnection._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._UpdateEkmConnection._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ekm_service.EkmConnection() + pb_resp = ekm_service.EkmConnection.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_ekm_connection(resp) + return resp + + class _VerifyConnectivity(_BaseEkmServiceRestTransport._BaseVerifyConnectivity, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.VerifyConnectivity") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: ekm_service.VerifyConnectivityRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> ekm_service.VerifyConnectivityResponse: + r"""Call the verify connectivity method over HTTP. + + Args: + request (~.ekm_service.VerifyConnectivityRequest): + The request object. Request message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.ekm_service.VerifyConnectivityResponse: + Response message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + + """ + + http_options = _BaseEkmServiceRestTransport._BaseVerifyConnectivity._get_http_options() + request, metadata = self._interceptor.pre_verify_connectivity(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseVerifyConnectivity._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseVerifyConnectivity._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._VerifyConnectivity._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = ekm_service.VerifyConnectivityResponse() + pb_resp = ekm_service.VerifyConnectivityResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_verify_connectivity(resp) + return resp + + @property + def create_ekm_connection(self) -> Callable[ + [ekm_service.CreateEkmConnectionRequest], + ekm_service.EkmConnection]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateEkmConnection(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_ekm_config(self) -> Callable[ + [ekm_service.GetEkmConfigRequest], + ekm_service.EkmConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEkmConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_ekm_connection(self) -> Callable[ + [ekm_service.GetEkmConnectionRequest], + ekm_service.EkmConnection]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetEkmConnection(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_ekm_connections(self) -> Callable[ + [ekm_service.ListEkmConnectionsRequest], + ekm_service.ListEkmConnectionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListEkmConnections(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_ekm_config(self) -> Callable[ + [ekm_service.UpdateEkmConfigRequest], + ekm_service.EkmConfig]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEkmConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_ekm_connection(self) -> Callable[ + [ekm_service.UpdateEkmConnectionRequest], + ekm_service.EkmConnection]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateEkmConnection(self._session, self._host, self._interceptor) # type: ignore + + @property + def verify_connectivity(self) -> Callable[ + [ekm_service.VerifyConnectivityRequest], + ekm_service.VerifyConnectivityResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._VerifyConnectivity(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseEkmServiceRestTransport._BaseGetLocation, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseEkmServiceRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseEkmServiceRestTransport._BaseListLocations, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseEkmServiceRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseEkmServiceRestTransport._BaseGetIamPolicy, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseEkmServiceRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseEkmServiceRestTransport._BaseSetIamPolicy, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseEkmServiceRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseEkmServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseEkmServiceRestTransport._BaseTestIamPermissions, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseEkmServiceRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseEkmServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseEkmServiceRestTransport._BaseGetOperation, EkmServiceRestStub): + def __hash__(self): + return hash("EkmServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, 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 = _BaseEkmServiceRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseEkmServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseEkmServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + # Send the request + response = EkmServiceRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'EkmServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest_base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest_base.py new file mode 100644 index 000000000000..440865818489 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest_base.py @@ -0,0 +1,602 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import EkmServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.kms_v1.types import ekm_service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseEkmServiceRestTransport(EkmServiceTransport): + """Base REST backend transport for EkmService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'cloudkms.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseCreateEkmConnection: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "ekmConnectionId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/ekmConnections', + 'body': 'ekm_connection', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ekm_service.CreateEkmConnectionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseEkmServiceRestTransport._BaseCreateEkmConnection._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEkmConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/ekmConfig}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ekm_service.GetEkmConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseEkmServiceRestTransport._BaseGetEkmConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetEkmConnection: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/ekmConnections/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ekm_service.GetEkmConnectionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseEkmServiceRestTransport._BaseGetEkmConnection._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListEkmConnections: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/ekmConnections', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ekm_service.ListEkmConnectionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseEkmServiceRestTransport._BaseListEkmConnections._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEkmConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{ekm_config.name=projects/*/locations/*/ekmConfig}', + 'body': 'ekm_config', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ekm_service.UpdateEkmConfigRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseEkmServiceRestTransport._BaseUpdateEkmConfig._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateEkmConnection: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{ekm_connection.name=projects/*/locations/*/ekmConnections/*}', + 'body': 'ekm_connection', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ekm_service.UpdateEkmConnectionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseEkmServiceRestTransport._BaseUpdateEkmConnection._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseVerifyConnectivity: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/ekmConnections/*}:verifyConnectivity', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = ekm_service.VerifyConnectivityRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseEkmServiceRestTransport._BaseVerifyConnectivity._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:getIamPolicy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseEkmServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/__init__.py new file mode 100644 index 000000000000..eec23330da9a --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .client import KeyManagementServiceClient +from .async_client import KeyManagementServiceAsyncClient + +__all__ = ( + 'KeyManagementServiceClient', + 'KeyManagementServiceAsyncClient', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/async_client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/async_client.py new file mode 100644 index 000000000000..519f45012e63 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -0,0 +1,4163 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union + +from google.cloud.kms_v1 import gapic_version as package_version + +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.kms_v1.services.key_management_service import pagers +from google.cloud.kms_v1.types import resources +from google.cloud.kms_v1.types import service +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport +from .client import KeyManagementServiceClient + + +class KeyManagementServiceAsyncClient: + """Google Cloud Key Management Service + + Manages cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [KeyRing][google.cloud.kms.v1.KeyRing] + - [CryptoKey][google.cloud.kms.v1.CryptoKey] + - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + - [ImportJob][google.cloud.kms.v1.ImportJob] + + If you are using manual gRPC libraries, see `Using gRPC with Cloud + KMS `__. + """ + + _client: KeyManagementServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = KeyManagementServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = KeyManagementServiceClient._DEFAULT_UNIVERSE + + crypto_key_path = staticmethod(KeyManagementServiceClient.crypto_key_path) + parse_crypto_key_path = staticmethod(KeyManagementServiceClient.parse_crypto_key_path) + crypto_key_version_path = staticmethod(KeyManagementServiceClient.crypto_key_version_path) + parse_crypto_key_version_path = staticmethod(KeyManagementServiceClient.parse_crypto_key_version_path) + import_job_path = staticmethod(KeyManagementServiceClient.import_job_path) + parse_import_job_path = staticmethod(KeyManagementServiceClient.parse_import_job_path) + key_ring_path = staticmethod(KeyManagementServiceClient.key_ring_path) + parse_key_ring_path = staticmethod(KeyManagementServiceClient.parse_key_ring_path) + public_key_path = staticmethod(KeyManagementServiceClient.public_key_path) + parse_public_key_path = staticmethod(KeyManagementServiceClient.parse_public_key_path) + common_billing_account_path = staticmethod(KeyManagementServiceClient.common_billing_account_path) + parse_common_billing_account_path = staticmethod(KeyManagementServiceClient.parse_common_billing_account_path) + common_folder_path = staticmethod(KeyManagementServiceClient.common_folder_path) + parse_common_folder_path = staticmethod(KeyManagementServiceClient.parse_common_folder_path) + common_organization_path = staticmethod(KeyManagementServiceClient.common_organization_path) + parse_common_organization_path = staticmethod(KeyManagementServiceClient.parse_common_organization_path) + common_project_path = staticmethod(KeyManagementServiceClient.common_project_path) + parse_common_project_path = staticmethod(KeyManagementServiceClient.parse_common_project_path) + common_location_path = staticmethod(KeyManagementServiceClient.common_location_path) + parse_common_location_path = staticmethod(KeyManagementServiceClient.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: + KeyManagementServiceAsyncClient: The constructed client. + """ + return KeyManagementServiceClient.from_service_account_info.__func__(KeyManagementServiceAsyncClient, 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: + KeyManagementServiceAsyncClient: The constructed client. + """ + return KeyManagementServiceClient.from_service_account_file.__func__(KeyManagementServiceAsyncClient, 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 KeyManagementServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> KeyManagementServiceTransport: + """Returns the transport used by the client instance. + + Returns: + KeyManagementServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = KeyManagementServiceClient.get_transport_class + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, KeyManagementServiceTransport, Callable[..., KeyManagementServiceTransport]]] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the key management service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,KeyManagementServiceTransport,Callable[..., KeyManagementServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the KeyManagementServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = KeyManagementServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + + ) + + async def list_key_rings(self, + request: Optional[Union[service.ListKeyRingsRequest, 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.ListKeyRingsAsyncPager: + r"""Lists [KeyRings][google.cloud.kms.v1.KeyRing]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_list_key_rings(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListKeyRingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_rings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ListKeyRingsRequest, dict]]): + The request object. Request message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + parent (:class:`str`): + Required. The resource name of the location associated + with the [KeyRings][google.cloud.kms.v1.KeyRing], in the + format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.services.key_management_service.pagers.ListKeyRingsAsyncPager: + Response message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListKeyRingsRequest): + request = service.ListKeyRingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_key_rings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListKeyRingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_crypto_keys(self, + request: Optional[Union[service.ListCryptoKeysRequest, 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.ListCryptoKeysAsyncPager: + r"""Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_list_crypto_keys(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListCryptoKeysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crypto_keys(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ListCryptoKeysRequest, dict]]): + The request object. Request message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + parent (:class:`str`): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeysAsyncPager: + Response message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListCryptoKeysRequest): + request = service.ListCryptoKeysRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_crypto_keys] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCryptoKeysAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_crypto_key_versions(self, + request: Optional[Union[service.ListCryptoKeyVersionsRequest, 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.ListCryptoKeyVersionsAsyncPager: + r"""Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_list_crypto_key_versions(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListCryptoKeyVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crypto_key_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest, dict]]): + The request object. Request message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + parent (:class:`str`): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in + the format + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsAsyncPager: + Response message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListCryptoKeyVersionsRequest): + request = service.ListCryptoKeyVersionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_crypto_key_versions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListCryptoKeyVersionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_import_jobs(self, + request: Optional[Union[service.ListImportJobsRequest, 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.ListImportJobsAsyncPager: + r"""Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_list_import_jobs(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListImportJobsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_import_jobs(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ListImportJobsRequest, dict]]): + The request object. Request message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + parent (:class:`str`): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.services.key_management_service.pagers.ListImportJobsAsyncPager: + Response message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListImportJobsRequest): + request = service.ListImportJobsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.list_import_jobs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListImportJobsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_key_ring(self, + request: Optional[Union[service.GetKeyRingRequest, 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]] = (), + ) -> resources.KeyRing: + r"""Returns metadata for a given + [KeyRing][google.cloud.kms.v1.KeyRing]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_get_key_ring(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetKeyRingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_key_ring(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GetKeyRingRequest, dict]]): + The request object. Request message for + [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. + name (:class:`str`): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the [KeyRing][google.cloud.kms.v1.KeyRing] to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.KeyRing: + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetKeyRingRequest): + request = service.GetKeyRingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_key_ring] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_crypto_key(self, + request: Optional[Union[service.GetCryptoKeyRequest, 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]] = (), + ) -> resources.CryptoKey: + r"""Returns metadata for a given + [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its + [primary][google.cloud.kms.v1.CryptoKey.primary] + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_get_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetCryptoKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_crypto_key(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GetCryptoKeyRequest, dict]]): + The request object. Request message for + [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. + name (:class:`str`): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] + of the [CryptoKey][google.cloud.kms.v1.CryptoKey] to + get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetCryptoKeyRequest): + request = service.GetCryptoKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_crypto_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_crypto_key_version(self, + request: Optional[Union[service.GetCryptoKeyVersionRequest, 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]] = (), + ) -> resources.CryptoKeyVersion: + r"""Returns metadata for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_get_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GetCryptoKeyVersionRequest, dict]]): + The request object. Request message for + [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetCryptoKeyVersionRequest): + request = service.GetCryptoKeyVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_public_key(self, + request: Optional[Union[service.GetPublicKeyRequest, 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]] = (), + ) -> resources.PublicKey: + r"""Returns the public key for the given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] + or + [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_get_public_key(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetPublicKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_public_key(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GetPublicKeyRequest, dict]]): + The request object. Request message for + [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + name (:class:`str`): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + public key to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.PublicKey: + The public keys for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + Obtained via + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetPublicKeyRequest): + request = service.GetPublicKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_public_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_import_job(self, + request: Optional[Union[service.GetImportJobRequest, 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]] = (), + ) -> resources.ImportJob: + r"""Returns metadata for a given + [ImportJob][google.cloud.kms.v1.ImportJob]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_get_import_job(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetImportJobRequest( + name="name_value", + ) + + # Make the request + response = await client.get_import_job(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GetImportJobRequest, dict]]): + The request object. Request message for + [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. + name (:class:`str`): + Required. The [name][google.cloud.kms.v1.ImportJob.name] + of the [ImportJob][google.cloud.kms.v1.ImportJob] to + get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetImportJobRequest): + request = service.GetImportJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.get_import_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_key_ring(self, + request: Optional[Union[service.CreateKeyRingRequest, dict]] = None, + *, + parent: Optional[str] = None, + key_ring_id: Optional[str] = None, + key_ring: Optional[resources.KeyRing] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyRing: + r"""Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given + Project and Location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_create_key_ring(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.CreateKeyRingRequest( + parent="parent_value", + key_ring_id="key_ring_id_value", + ) + + # Make the request + response = await client.create_key_ring(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.CreateKeyRingRequest, dict]]): + The request object. Request message for + [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. + parent (:class:`str`): + Required. The resource name of the location associated + with the [KeyRings][google.cloud.kms.v1.KeyRing], in the + format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_ring_id (:class:`str`): + Required. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}`` + + This corresponds to the ``key_ring_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_ring (:class:`google.cloud.kms_v1.types.KeyRing`): + Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with + initial field values. + + This corresponds to the ``key_ring`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.KeyRing: + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, key_ring_id, key_ring]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateKeyRingRequest): + request = service.CreateKeyRingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if key_ring_id is not None: + request.key_ring_id = key_ring_id + if key_ring is not None: + request.key_ring = key_ring + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_key_ring] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_crypto_key(self, + request: Optional[Union[service.CreateCryptoKeyRequest, dict]] = None, + *, + parent: Optional[str] = None, + crypto_key_id: Optional[str] = None, + crypto_key: Optional[resources.CryptoKey] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and + [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] + are required. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_create_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.CreateCryptoKeyRequest( + parent="parent_value", + crypto_key_id="crypto_key_id_value", + ) + + # Make the request + response = await client.create_crypto_key(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.CreateCryptoKeyRequest, dict]]): + The request object. Request message for + [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. + parent (:class:`str`): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the KeyRing associated with the + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_id (:class:`str`): + Required. It must be unique within a KeyRing and match + the regular expression ``[a-zA-Z0-9_-]{1,63}`` + + This corresponds to the ``crypto_key_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key (:class:`google.cloud.kms_v1.types.CryptoKey`): + Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] + with initial field values. + + This corresponds to the ``crypto_key`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, crypto_key_id, crypto_key]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateCryptoKeyRequest): + request = service.CreateCryptoKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if crypto_key_id is not None: + request.crypto_key_id = crypto_key_id + if crypto_key is not None: + request.crypto_key = crypto_key + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_crypto_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_crypto_key_version(self, + request: Optional[Union[service.CreateCryptoKeyVersionRequest, dict]] = None, + *, + parent: Optional[str] = None, + crypto_key_version: Optional[resources.CryptoKeyVersion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Create a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The server will assign the next sequential id. If unset, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_create_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.CreateCryptoKeyVersionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest, dict]]): + The request object. Request message for + [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. + parent (:class:`str`): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] + of the [CryptoKey][google.cloud.kms.v1.CryptoKey] + associated with the + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_version (:class:`google.cloud.kms_v1.types.CryptoKeyVersion`): + Required. A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with initial field values. + + This corresponds to the ``crypto_key_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, crypto_key_version]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateCryptoKeyVersionRequest): + request = service.CreateCryptoKeyVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if crypto_key_version is not None: + request.crypto_key_version = crypto_key_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def import_crypto_key_version(self, + request: Optional[Union[service.ImportCryptoKeyVersionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_import_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ImportCryptoKeyVersionRequest( + rsa_aes_wrapped_key=b'rsa_aes_wrapped_key_blob', + parent="parent_value", + algorithm="EXTERNAL_SYMMETRIC_ENCRYPTION", + import_job="import_job_value", + ) + + # Make the request + response = await client.import_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest, dict]]): + The request object. Request message for + [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ImportCryptoKeyVersionRequest): + request = service.ImportCryptoKeyVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.import_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_import_job(self, + request: Optional[Union[service.CreateImportJobRequest, dict]] = None, + *, + parent: Optional[str] = None, + import_job_id: Optional[str] = None, + import_job: Optional[resources.ImportJob] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ImportJob: + r"""Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] + is required. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_create_import_job(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + import_job = kms_v1.ImportJob() + import_job.import_method = "RSA_OAEP_4096_SHA256" + import_job.protection_level = "EXTERNAL_VPC" + + request = kms_v1.CreateImportJobRequest( + parent="parent_value", + import_job_id="import_job_id_value", + import_job=import_job, + ) + + # Make the request + response = await client.create_import_job(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.CreateImportJobRequest, dict]]): + The request object. Request message for + [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. + parent (:class:`str`): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the [KeyRing][google.cloud.kms.v1.KeyRing] associated + with the [ImportJobs][google.cloud.kms.v1.ImportJob]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + import_job_id (:class:`str`): + Required. It must be unique within a KeyRing and match + the regular expression ``[a-zA-Z0-9_-]{1,63}`` + + This corresponds to the ``import_job_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + import_job (:class:`google.cloud.kms_v1.types.ImportJob`): + Required. An [ImportJob][google.cloud.kms.v1.ImportJob] + with initial field values. + + This corresponds to the ``import_job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). + + """ + # Create or coerce a protobuf request object. + # - Quick 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, import_job_id, import_job]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateImportJobRequest): + request = service.CreateImportJobRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if import_job_id is not None: + request.import_job_id = import_job_id + if import_job is not None: + request.import_job = import_job + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.create_import_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_crypto_key(self, + request: Optional[Union[service.UpdateCryptoKeyRequest, dict]] = None, + *, + crypto_key: Optional[resources.CryptoKey] = 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]] = (), + ) -> resources.CryptoKey: + r"""Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_update_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyRequest( + ) + + # Make the request + response = await client.update_crypto_key(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.UpdateCryptoKeyRequest, dict]]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. + crypto_key (:class:`google.cloud.kms_v1.types.CryptoKey`): + Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] + with updated values. + + This corresponds to the ``crypto_key`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([crypto_key, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateCryptoKeyRequest): + request = service.UpdateCryptoKeyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if crypto_key is not None: + request.crypto_key = crypto_key + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_crypto_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("crypto_key.name", request.crypto_key.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_crypto_key_version(self, + request: Optional[Union[service.UpdateCryptoKeyVersionRequest, dict]] = None, + *, + crypto_key_version: Optional[resources.CryptoKeyVersion] = 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]] = (), + ) -> resources.CryptoKeyVersion: + r"""Update a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + metadata. + + [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be + changed between + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + and + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] + using this method. See + [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] + and + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + to move between other states. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_update_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyVersionRequest( + ) + + # Make the request + response = await client.update_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest, dict]]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. + crypto_key_version (:class:`google.cloud.kms_v1.types.CryptoKeyVersion`): + Required. + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with updated values. + + This corresponds to the ``crypto_key_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Required. List of fields to be + updated in this request. + + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([crypto_key_version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateCryptoKeyVersionRequest): + request = service.UpdateCryptoKeyVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if crypto_key_version is not None: + request.crypto_key_version = crypto_key_version + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("crypto_key_version.name", request.crypto_key_version.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_crypto_key_primary_version(self, + request: Optional[Union[service.UpdateCryptoKeyPrimaryVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + crypto_key_version_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Update the version of a + [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Returns an error if called on a key whose purpose is not + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_update_crypto_key_primary_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyPrimaryVersionRequest( + name="name_value", + crypto_key_version_id="crypto_key_version_id_value", + ) + + # Make the request + response = await client.update_crypto_key_primary_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest, dict]]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. + name (:class:`str`): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_version_id (:class:`str`): + Required. The id of the child + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use as primary. + + This corresponds to the ``crypto_key_version_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, crypto_key_version_id]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateCryptoKeyPrimaryVersionRequest): + request = service.UpdateCryptoKeyPrimaryVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if crypto_key_version_id is not None: + request.crypto_key_version_id = crypto_key_version_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.update_crypto_key_primary_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def destroy_crypto_key_version(self, + request: Optional[Union[service.DestroyCryptoKeyVersionRequest, 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]] = (), + ) -> resources.CryptoKeyVersion: + r"""Schedule a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for + destruction. + + Upon calling this method, + [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] + will be set to + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be set to the time + [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] + in the future. At that time, the + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will + automatically change to + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], + and the key material will be irrevocably destroyed. + + Before the + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + is reached, + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + may be called to reverse the process. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_destroy_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.DestroyCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.destroy_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest, dict]]): + The request object. Request message for + [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to destroy. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DestroyCryptoKeyVersionRequest): + request = service.DestroyCryptoKeyVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.destroy_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def restore_crypto_key_version(self, + request: Optional[Union[service.RestoreCryptoKeyVersionRequest, 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]] = (), + ) -> resources.CryptoKeyVersion: + r"""Restore a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] + state. + + Upon restoration of the CryptoKeyVersion, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be cleared. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_restore_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.RestoreCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.restore_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest, dict]]): + The request object. Request message for + [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to restore. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.RestoreCryptoKeyVersionRequest): + request = service.RestoreCryptoKeyVersionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.restore_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def encrypt(self, + request: Optional[Union[service.EncryptRequest, dict]] = None, + *, + name: Optional[str] = None, + plaintext: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.EncryptResponse: + r"""Encrypts data, so that it can only be recovered by a call to + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_encrypt(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.EncryptRequest( + name="name_value", + plaintext=b'plaintext_blob', + ) + + # Make the request + response = await client.encrypt(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.EncryptRequest, dict]]): + The request object. Request message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + name (:class:`str`): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] or + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for encryption. + + If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is + specified, the server will use its [primary + version][google.cloud.kms.v1.CryptoKey.primary]. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + plaintext (:class:`bytes`): + Required. The data to encrypt. Must be no larger than + 64KiB. + + The maximum size depends on the key version's + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. + For + [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE], + [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL], + and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + keys, the plaintext must be no larger than 64KiB. For + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the + combined length of the plaintext and + additional_authenticated_data fields must be no larger + than 8KiB. + + This corresponds to the ``plaintext`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EncryptResponse: + Response message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, plaintext]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.EncryptRequest): + request = service.EncryptRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if plaintext is not None: + request.plaintext = plaintext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.encrypt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def decrypt(self, + request: Optional[Union[service.DecryptRequest, dict]] = None, + *, + name: Optional[str] = None, + ciphertext: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.DecryptResponse: + r"""Decrypts data that was protected by + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.DecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + ) + + # Make the request + response = await client.decrypt(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.DecryptRequest, dict]]): + The request object. Request message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + name (:class:`str`): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for + decryption. The server will choose the appropriate + version. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ciphertext (:class:`bytes`): + Required. The encrypted data originally returned in + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. + + This corresponds to the ``ciphertext`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.DecryptResponse: + Response message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, ciphertext]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DecryptRequest): + request = service.DecryptRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ciphertext is not None: + request.ciphertext = ciphertext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.decrypt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def raw_encrypt(self, + request: Optional[Union[service.RawEncryptRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.RawEncryptResponse: + r"""Encrypts data using portable cryptographic primitives. Most + users should choose + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] and + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt] + rather than their raw counterparts. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_raw_encrypt(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.RawEncryptRequest( + name="name_value", + plaintext=b'plaintext_blob', + ) + + # Make the request + response = await client.raw_encrypt(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.RawEncryptRequest, dict]]): + The request object. Request message for + [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.RawEncryptResponse: + Response message for + [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.RawEncryptRequest): + request = service.RawEncryptRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.raw_encrypt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def raw_decrypt(self, + request: Optional[Union[service.RawDecryptRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.RawDecryptResponse: + r"""Decrypts data that was originally encrypted using a raw + cryptographic mechanism. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_raw_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.RawDecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + initialization_vector=b'initialization_vector_blob', + ) + + # Make the request + response = await client.raw_decrypt(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.RawDecryptRequest, dict]]): + The request object. Request message for + [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.RawDecryptResponse: + Response message for + [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.RawDecryptRequest): + request = service.RawDecryptRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.raw_decrypt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def asymmetric_sign(self, + request: Optional[Union[service.AsymmetricSignRequest, dict]] = None, + *, + name: Optional[str] = None, + digest: Optional[service.Digest] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AsymmetricSignResponse: + r"""Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_SIGN, producing a signature that can be verified with + the public key retrieved from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_asymmetric_sign(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.AsymmetricSignRequest( + name="name_value", + ) + + # Make the request + response = await client.asymmetric_sign(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.AsymmetricSignRequest, dict]]): + The request object. Request message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for signing. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + digest (:class:`google.cloud.kms_v1.types.Digest`): + Optional. The digest of the data to sign. The digest + must be produced with the same digest algorithm as + specified by the key version's + [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + + This field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. + + This corresponds to the ``digest`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.AsymmetricSignResponse: + Response message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, digest]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.AsymmetricSignRequest): + request = service.AsymmetricSignRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if digest is not None: + request.digest = digest + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.asymmetric_sign] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def asymmetric_decrypt(self, + request: Optional[Union[service.AsymmetricDecryptRequest, dict]] = None, + *, + name: Optional[str] = None, + ciphertext: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AsymmetricDecryptResponse: + r"""Decrypts data that was encrypted with a public key retrieved + from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] + corresponding to a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_DECRYPT. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_asymmetric_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.AsymmetricDecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + ) + + # Make the request + response = await client.asymmetric_decrypt(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.AsymmetricDecryptRequest, dict]]): + The request object. Request message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for decryption. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ciphertext (:class:`bytes`): + Required. The data encrypted with the named + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + public key using OAEP. + + This corresponds to the ``ciphertext`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.AsymmetricDecryptResponse: + Response message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, ciphertext]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.AsymmetricDecryptRequest): + request = service.AsymmetricDecryptRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ciphertext is not None: + request.ciphertext = ciphertext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.asymmetric_decrypt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def mac_sign(self, + request: Optional[Union[service.MacSignRequest, dict]] = None, + *, + name: Optional[str] = None, + data: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.MacSignResponse: + r"""Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + producing a tag that can be verified by another source with the + same key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_mac_sign(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.MacSignRequest( + name="name_value", + data=b'data_blob', + ) + + # Make the request + response = await client.mac_sign(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.MacSignRequest, dict]]): + The request object. Request message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for signing. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (:class:`bytes`): + Required. The data to sign. The MAC + tag is computed over this data field + based on the specific algorithm. + + This corresponds to the ``data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.MacSignResponse: + Response message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, data]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.MacSignRequest): + request = service.MacSignRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.mac_sign] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def mac_verify(self, + request: Optional[Union[service.MacVerifyRequest, dict]] = None, + *, + name: Optional[str] = None, + data: Optional[bytes] = None, + mac: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.MacVerifyResponse: + r"""Verifies MAC tag using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + and returns a response that indicates whether or not the + verification was successful. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + async def sample_mac_verify(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.MacVerifyRequest( + name="name_value", + data=b'data_blob', + mac=b'mac_blob', + ) + + # Make the request + response = await client.mac_verify(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.MacVerifyRequest, dict]]): + The request object. Request message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + name (:class:`str`): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for verification. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (:class:`bytes`): + Required. The data used previously as a + [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] + to generate the MAC tag. + + This corresponds to the ``data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mac (:class:`bytes`): + Required. The signature to verify. + This corresponds to the ``mac`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.MacVerifyResponse: + Response message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, data, mac]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.MacVerifyRequest): + request = service.MacVerifyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + if mac is not None: + request.mac = mac + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.mac_verify] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def generate_random_bytes(self, + request: Optional[Union[service.GenerateRandomBytesRequest, dict]] = None, + *, + location: Optional[str] = None, + length_bytes: Optional[int] = None, + protection_level: Optional[resources.ProtectionLevel] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateRandomBytesResponse: + r"""Generate random bytes using the Cloud KMS randomness + source in the 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 import kms_v1 + + async def sample_generate_random_bytes(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GenerateRandomBytesRequest( + ) + + # Make the request + response = await client.generate_random_bytes(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.GenerateRandomBytesRequest, dict]]): + The request object. Request message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + location (:class:`str`): + The project-specific location in + which to generate random bytes. For + example, + "projects/my-project/locations/us-central1". + + This corresponds to the ``location`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + length_bytes (:class:`int`): + The length in bytes of the amount of + randomness to retrieve. Minimum 8 + bytes, maximum 1024 bytes. + + This corresponds to the ``length_bytes`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + protection_level (:class:`google.cloud.kms_v1.types.ProtectionLevel`): + The + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + to use when generating the random data. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] + protection level is supported. + + This corresponds to the ``protection_level`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.GenerateRandomBytesResponse: + Response message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([location, length_bytes, protection_level]) + if request is not None and has_flattened_params: + raise ValueError("If the `request` argument is set, then none of " + "the individual field arguments should be set.") + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GenerateRandomBytesRequest): + request = service.GenerateRandomBytesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if location is not None: + request.location = location + if length_bytes is not None: + request.length_bytes = length_bytes + if protection_level is not None: + request.protection_level = protection_level + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[self._client._transport.generate_random_bytes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("location", request.location), + )), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does + not have a policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified permissions against the IAM access control + policy for a function. + + If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~iam_policy_pb2.PolicyTestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def __aenter__(self) -> "KeyManagementServiceAsyncClient": + 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__ = ( + "KeyManagementServiceAsyncClient", +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/client.py new file mode 100644 index 000000000000..2d95b5dc202f --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/client.py @@ -0,0 +1,4517 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast +import warnings + +from google.cloud.kms_v1 import gapic_version as package_version + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.cloud.kms_v1.services.key_management_service import pagers +from google.cloud.kms_v1.types import resources +from google.cloud.kms_v1.types import service +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +from .transports.base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import KeyManagementServiceGrpcTransport +from .transports.grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport +from .transports.rest import KeyManagementServiceRestTransport + + +class KeyManagementServiceClientMeta(type): + """Metaclass for the KeyManagementService 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[KeyManagementServiceTransport]] + _transport_registry["grpc"] = KeyManagementServiceGrpcTransport + _transport_registry["grpc_asyncio"] = KeyManagementServiceGrpcAsyncIOTransport + _transport_registry["rest"] = KeyManagementServiceRestTransport + + def get_transport_class(cls, + label: Optional[str] = None, + ) -> Type[KeyManagementServiceTransport]: + """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 KeyManagementServiceClient(metaclass=KeyManagementServiceClientMeta): + """Google Cloud Key Management Service + + Manages cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [KeyRing][google.cloud.kms.v1.KeyRing] + - [CryptoKey][google.cloud.kms.v1.CryptoKey] + - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + - [ImportJob][google.cloud.kms.v1.ImportJob] + + If you are using manual gRPC libraries, see `Using gRPC with Cloud + KMS `__. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "cloudkms.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "cloudkms.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + KeyManagementServiceClient: 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: + KeyManagementServiceClient: 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) -> KeyManagementServiceTransport: + """Returns the transport used by the client instance. + + Returns: + KeyManagementServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str,str]: + """Parses a crypto_key path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_version_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: + """Returns a fully-qualified crypto_key_version string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + + @staticmethod + def parse_crypto_key_version_path(path: str) -> Dict[str,str]: + """Parses a crypto_key_version path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def import_job_path(project: str,location: str,key_ring: str,import_job: str,) -> str: + """Returns a fully-qualified import_job string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format(project=project, location=location, key_ring=key_ring, import_job=import_job, ) + + @staticmethod + def parse_import_job_path(path: str) -> Dict[str,str]: + """Parses a import_job path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/importJobs/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def key_ring_path(project: str,location: str,key_ring: str,) -> str: + """Returns a fully-qualified key_ring string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}".format(project=project, location=location, key_ring=key_ring, ) + + @staticmethod + def parse_key_ring_path(path: str) -> Dict[str,str]: + """Parses a key_ring path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def public_key_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: + """Returns a fully-qualified public_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + + @staticmethod + def parse_public_key_path(path: str) -> Dict[str,str]: + """Parses a public_key path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)/publicKey$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str, ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str,str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str, ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder, ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str,str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str, ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization, ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str,str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str, ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format(project=project, ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str,str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str, ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format(project=project, location=location, ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str,str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): + _default_universe = KeyManagementServiceClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") + api_endpoint = KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) + return api_endpoint + + @staticmethod + def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = KeyManagementServiceClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__(self, *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, KeyManagementServiceTransport, Callable[..., KeyManagementServiceTransport]]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the key management service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,KeyManagementServiceTransport,Callable[..., KeyManagementServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the KeyManagementServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast(client_options_lib.ClientOptions, self._client_options) + + universe_domain_opt = getattr(self._client_options, 'universe_domain', None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = KeyManagementServiceClient._read_environment_variables() + self._client_cert_source = KeyManagementServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) + self._universe_domain = KeyManagementServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError("client_options.api_key and credentials are mutually exclusive") + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, KeyManagementServiceTransport) + if transport_provided: + # transport is a KeyManagementServiceTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError("When providing a transport instance, " + "provide its credentials directly.") + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(KeyManagementServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = (self._api_endpoint or + KeyManagementServiceClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint)) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): + credentials = google.auth._default.get_api_key_credentials(api_key_value) + + transport_init: Union[Type[KeyManagementServiceTransport], Callable[..., KeyManagementServiceTransport]] = ( + KeyManagementServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., KeyManagementServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def list_key_rings(self, + request: Optional[Union[service.ListKeyRingsRequest, 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.ListKeyRingsPager: + r"""Lists [KeyRings][google.cloud.kms.v1.KeyRing]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_list_key_rings(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ListKeyRingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_rings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ListKeyRingsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + parent (str): + Required. The resource name of the location associated + with the [KeyRings][google.cloud.kms.v1.KeyRing], in the + format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.services.key_management_service.pagers.ListKeyRingsPager: + Response message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListKeyRingsRequest): + request = service.ListKeyRingsRequest(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_key_rings] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListKeyRingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_crypto_keys(self, + request: Optional[Union[service.ListCryptoKeysRequest, 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.ListCryptoKeysPager: + r"""Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_list_crypto_keys(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ListCryptoKeysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crypto_keys(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ListCryptoKeysRequest, dict]): + The request object. Request message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + parent (str): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + + 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.kms_v1.services.key_management_service.pagers.ListCryptoKeysPager: + Response message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListCryptoKeysRequest): + request = service.ListCryptoKeysRequest(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_crypto_keys] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCryptoKeysPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_crypto_key_versions(self, + request: Optional[Union[service.ListCryptoKeyVersionsRequest, 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.ListCryptoKeyVersionsPager: + r"""Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_list_crypto_key_versions(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ListCryptoKeyVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crypto_key_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + parent (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in + the format + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + + 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.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsPager: + Response message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListCryptoKeyVersionsRequest): + request = service.ListCryptoKeyVersionsRequest(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_crypto_key_versions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListCryptoKeyVersionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_import_jobs(self, + request: Optional[Union[service.ListImportJobsRequest, 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.ListImportJobsPager: + r"""Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_list_import_jobs(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ListImportJobsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_import_jobs(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ListImportJobsRequest, dict]): + The request object. Request message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + parent (str): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + + 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.kms_v1.services.key_management_service.pagers.ListImportJobsPager: + Response message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListImportJobsRequest): + request = service.ListImportJobsRequest(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_import_jobs] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListImportJobsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_key_ring(self, + request: Optional[Union[service.GetKeyRingRequest, 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]] = (), + ) -> resources.KeyRing: + r"""Returns metadata for a given + [KeyRing][google.cloud.kms.v1.KeyRing]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_get_key_ring(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetKeyRingRequest( + name="name_value", + ) + + # Make the request + response = client.get_key_ring(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GetKeyRingRequest, dict]): + The request object. Request message for + [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. + name (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the [KeyRing][google.cloud.kms.v1.KeyRing] to get. + + 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.kms_v1.types.KeyRing: + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetKeyRingRequest): + request = service.GetKeyRingRequest(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_key_ring] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_crypto_key(self, + request: Optional[Union[service.GetCryptoKeyRequest, 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]] = (), + ) -> resources.CryptoKey: + r"""Returns metadata for a given + [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its + [primary][google.cloud.kms.v1.CryptoKey.primary] + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_get_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetCryptoKeyRequest( + name="name_value", + ) + + # Make the request + response = client.get_crypto_key(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GetCryptoKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. + name (str): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] + of the [CryptoKey][google.cloud.kms.v1.CryptoKey] to + get. + + 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.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetCryptoKeyRequest): + request = service.GetCryptoKeyRequest(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_crypto_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_crypto_key_version(self, + request: Optional[Union[service.GetCryptoKeyVersionRequest, 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]] = (), + ) -> resources.CryptoKeyVersion: + r"""Returns metadata for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_get_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GetCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. + name (str): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to get. + + 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.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetCryptoKeyVersionRequest): + request = service.GetCryptoKeyVersionRequest(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_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_public_key(self, + request: Optional[Union[service.GetPublicKeyRequest, 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]] = (), + ) -> resources.PublicKey: + r"""Returns the public key for the given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] + or + [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_get_public_key(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetPublicKeyRequest( + name="name_value", + ) + + # Make the request + response = client.get_public_key(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GetPublicKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + name (str): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + public key to get. + + 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.kms_v1.types.PublicKey: + The public keys for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + Obtained via + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetPublicKeyRequest): + request = service.GetPublicKeyRequest(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_public_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_import_job(self, + request: Optional[Union[service.GetImportJobRequest, 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]] = (), + ) -> resources.ImportJob: + r"""Returns metadata for a given + [ImportJob][google.cloud.kms.v1.ImportJob]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_get_import_job(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetImportJobRequest( + name="name_value", + ) + + # Make the request + response = client.get_import_job(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GetImportJobRequest, dict]): + The request object. Request message for + [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. + name (str): + Required. The [name][google.cloud.kms.v1.ImportJob.name] + of the [ImportJob][google.cloud.kms.v1.ImportJob] to + get. + + 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.kms_v1.types.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GetImportJobRequest): + request = service.GetImportJobRequest(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_import_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_key_ring(self, + request: Optional[Union[service.CreateKeyRingRequest, dict]] = None, + *, + parent: Optional[str] = None, + key_ring_id: Optional[str] = None, + key_ring: Optional[resources.KeyRing] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.KeyRing: + r"""Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given + Project and Location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_create_key_ring(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.CreateKeyRingRequest( + parent="parent_value", + key_ring_id="key_ring_id_value", + ) + + # Make the request + response = client.create_key_ring(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.CreateKeyRingRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. + parent (str): + Required. The resource name of the location associated + with the [KeyRings][google.cloud.kms.v1.KeyRing], in the + format ``projects/*/locations/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_ring_id (str): + Required. It must be unique within a location and match + the regular expression ``[a-zA-Z0-9_-]{1,63}`` + + This corresponds to the ``key_ring_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + key_ring (google.cloud.kms_v1.types.KeyRing): + Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with + initial field values. + + This corresponds to the ``key_ring`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.KeyRing: + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, key_ring_id, key_ring]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateKeyRingRequest): + request = service.CreateKeyRingRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if key_ring_id is not None: + request.key_ring_id = key_ring_id + if key_ring is not None: + request.key_ring = key_ring + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_key_ring] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_crypto_key(self, + request: Optional[Union[service.CreateCryptoKeyRequest, dict]] = None, + *, + parent: Optional[str] = None, + crypto_key_id: Optional[str] = None, + crypto_key: Optional[resources.CryptoKey] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and + [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] + are required. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_create_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.CreateCryptoKeyRequest( + parent="parent_value", + crypto_key_id="crypto_key_id_value", + ) + + # Make the request + response = client.create_crypto_key(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.CreateCryptoKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. + parent (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the KeyRing associated with the + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_id (str): + Required. It must be unique within a KeyRing and match + the regular expression ``[a-zA-Z0-9_-]{1,63}`` + + This corresponds to the ``crypto_key_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key (google.cloud.kms_v1.types.CryptoKey): + Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] + with initial field values. + + This corresponds to the ``crypto_key`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, crypto_key_id, crypto_key]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateCryptoKeyRequest): + request = service.CreateCryptoKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if crypto_key_id is not None: + request.crypto_key_id = crypto_key_id + if crypto_key is not None: + request.crypto_key = crypto_key + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_crypto_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_crypto_key_version(self, + request: Optional[Union[service.CreateCryptoKeyVersionRequest, dict]] = None, + *, + parent: Optional[str] = None, + crypto_key_version: Optional[resources.CryptoKeyVersion] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Create a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The server will assign the next sequential id. If unset, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_create_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.CreateCryptoKeyVersionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. + parent (str): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] + of the [CryptoKey][google.cloud.kms.v1.CryptoKey] + associated with the + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): + Required. A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with initial field values. + + This corresponds to the ``crypto_key_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, crypto_key_version]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateCryptoKeyVersionRequest): + request = service.CreateCryptoKeyVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if crypto_key_version is not None: + request.crypto_key_version = crypto_key_version + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def import_crypto_key_version(self, + request: Optional[Union[service.ImportCryptoKeyVersionRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKeyVersion: + r"""Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_import_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ImportCryptoKeyVersionRequest( + rsa_aes_wrapped_key=b'rsa_aes_wrapped_key_blob', + parent="parent_value", + algorithm="EXTERNAL_SYMMETRIC_ENCRYPTION", + import_job="import_job_value", + ) + + # Make the request + response = client.import_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ImportCryptoKeyVersionRequest): + request = service.ImportCryptoKeyVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.import_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_import_job(self, + request: Optional[Union[service.CreateImportJobRequest, dict]] = None, + *, + parent: Optional[str] = None, + import_job_id: Optional[str] = None, + import_job: Optional[resources.ImportJob] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ImportJob: + r"""Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] + is required. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_create_import_job(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + import_job = kms_v1.ImportJob() + import_job.import_method = "RSA_OAEP_4096_SHA256" + import_job.protection_level = "EXTERNAL_VPC" + + request = kms_v1.CreateImportJobRequest( + parent="parent_value", + import_job_id="import_job_id_value", + import_job=import_job, + ) + + # Make the request + response = client.create_import_job(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.CreateImportJobRequest, dict]): + The request object. Request message for + [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. + parent (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] + of the [KeyRing][google.cloud.kms.v1.KeyRing] associated + with the [ImportJobs][google.cloud.kms.v1.ImportJob]. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + import_job_id (str): + Required. It must be unique within a KeyRing and match + the regular expression ``[a-zA-Z0-9_-]{1,63}`` + + This corresponds to the ``import_job_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + import_job (google.cloud.kms_v1.types.ImportJob): + Required. An [ImportJob][google.cloud.kms.v1.ImportJob] + with initial field values. + + This corresponds to the ``import_job`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", + which is a public/private key pair. You use the + wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the + import process. The nature of the wrapping key + depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be + set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be + used to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires + 3 days after it is created. Once expired, Cloud KMS + will no longer be able to import or unwrap any key + material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public + key. + + For more information, see [Importing a + key](\ https://cloud.google.com/kms/docs/importing-a-key). + + """ + # Create or coerce a protobuf request object. + # - Quick 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, import_job_id, import_job]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.CreateImportJobRequest): + request = service.CreateImportJobRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if import_job_id is not None: + request.import_job_id = import_job_id + if import_job is not None: + request.import_job = import_job + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_import_job] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("parent", request.parent), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_crypto_key(self, + request: Optional[Union[service.UpdateCryptoKeyRequest, dict]] = None, + *, + crypto_key: Optional[resources.CryptoKey] = 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]] = (), + ) -> resources.CryptoKey: + r"""Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_update_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyRequest( + ) + + # Make the request + response = client.update_crypto_key(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. + crypto_key (google.cloud.kms_v1.types.CryptoKey): + Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] + with updated values. + + This corresponds to the ``crypto_key`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + 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.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([crypto_key, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateCryptoKeyRequest): + request = service.UpdateCryptoKeyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if crypto_key is not None: + request.crypto_key = crypto_key + 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_crypto_key] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("crypto_key.name", request.crypto_key.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_crypto_key_version(self, + request: Optional[Union[service.UpdateCryptoKeyVersionRequest, dict]] = None, + *, + crypto_key_version: Optional[resources.CryptoKeyVersion] = 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]] = (), + ) -> resources.CryptoKeyVersion: + r"""Update a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + metadata. + + [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be + changed between + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + and + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] + using this method. See + [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] + and + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + to move between other states. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_update_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyVersionRequest( + ) + + # Make the request + response = client.update_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): + Required. + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with updated values. + + This corresponds to the ``crypto_key_version`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be + updated in this request. + + 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.cloud.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([crypto_key_version, update_mask]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateCryptoKeyVersionRequest): + request = service.UpdateCryptoKeyVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if crypto_key_version is not None: + request.crypto_key_version = crypto_key_version + 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_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("crypto_key_version.name", request.crypto_key_version.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_crypto_key_primary_version(self, + request: Optional[Union[service.UpdateCryptoKeyPrimaryVersionRequest, dict]] = None, + *, + name: Optional[str] = None, + crypto_key_version_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.CryptoKey: + r"""Update the version of a + [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Returns an error if called on a key whose purpose is not + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_update_crypto_key_primary_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyPrimaryVersionRequest( + name="name_value", + crypto_key_version_id="crypto_key_version_id_value", + ) + + # Make the request + response = client.update_crypto_key_primary_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + crypto_key_version_id (str): + Required. The id of the child + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use as primary. + + This corresponds to the ``crypto_key_version_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that + can be used for cryptographic operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made + up of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], + which represent the actual key material used in + cryptographic operations. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, crypto_key_version_id]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.UpdateCryptoKeyPrimaryVersionRequest): + request = service.UpdateCryptoKeyPrimaryVersionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if crypto_key_version_id is not None: + request.crypto_key_version_id = crypto_key_version_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_crypto_key_primary_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def destroy_crypto_key_version(self, + request: Optional[Union[service.DestroyCryptoKeyVersionRequest, 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]] = (), + ) -> resources.CryptoKeyVersion: + r"""Schedule a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for + destruction. + + Upon calling this method, + [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] + will be set to + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be set to the time + [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] + in the future. At that time, the + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will + automatically change to + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], + and the key material will be irrevocably destroyed. + + Before the + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + is reached, + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + may be called to reverse the process. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_destroy_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.DestroyCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = client.destroy_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to destroy. + + 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.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DestroyCryptoKeyVersionRequest): + request = service.DestroyCryptoKeyVersionRequest(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.destroy_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def restore_crypto_key_version(self, + request: Optional[Union[service.RestoreCryptoKeyVersionRequest, 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]] = (), + ) -> resources.CryptoKeyVersion: + r"""Restore a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] + state. + + Upon restoration of the CryptoKeyVersion, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be cleared. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_restore_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.RestoreCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = client.restore_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to restore. + + 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.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.RestoreCryptoKeyVersionRequest): + request = service.RestoreCryptoKeyVersionRequest(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.restore_crypto_key_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def encrypt(self, + request: Optional[Union[service.EncryptRequest, dict]] = None, + *, + name: Optional[str] = None, + plaintext: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.EncryptResponse: + r"""Encrypts data, so that it can only be recovered by a call to + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_encrypt(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.EncryptRequest( + name="name_value", + plaintext=b'plaintext_blob', + ) + + # Make the request + response = client.encrypt(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.EncryptRequest, dict]): + The request object. Request message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] or + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for encryption. + + If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is + specified, the server will use its [primary + version][google.cloud.kms.v1.CryptoKey.primary]. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + plaintext (bytes): + Required. The data to encrypt. Must be no larger than + 64KiB. + + The maximum size depends on the key version's + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. + For + [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE], + [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL], + and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + keys, the plaintext must be no larger than 64KiB. For + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the + combined length of the plaintext and + additional_authenticated_data fields must be no larger + than 8KiB. + + This corresponds to the ``plaintext`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.EncryptResponse: + Response message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, plaintext]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.EncryptRequest): + request = service.EncryptRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if plaintext is not None: + request.plaintext = plaintext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.encrypt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def decrypt(self, + request: Optional[Union[service.DecryptRequest, dict]] = None, + *, + name: Optional[str] = None, + ciphertext: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.DecryptResponse: + r"""Decrypts data that was protected by + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.DecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + ) + + # Make the request + response = client.decrypt(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.DecryptRequest, dict]): + The request object. Request message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for + decryption. The server will choose the appropriate + version. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ciphertext (bytes): + Required. The encrypted data originally returned in + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. + + This corresponds to the ``ciphertext`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.DecryptResponse: + Response message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, ciphertext]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.DecryptRequest): + request = service.DecryptRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ciphertext is not None: + request.ciphertext = ciphertext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.decrypt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def raw_encrypt(self, + request: Optional[Union[service.RawEncryptRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.RawEncryptResponse: + r"""Encrypts data using portable cryptographic primitives. Most + users should choose + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] and + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt] + rather than their raw counterparts. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_raw_encrypt(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.RawEncryptRequest( + name="name_value", + plaintext=b'plaintext_blob', + ) + + # Make the request + response = client.raw_encrypt(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.RawEncryptRequest, dict]): + The request object. Request message for + [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.RawEncryptResponse: + Response message for + [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.RawEncryptRequest): + request = service.RawEncryptRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.raw_encrypt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def raw_decrypt(self, + request: Optional[Union[service.RawDecryptRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.RawDecryptResponse: + r"""Decrypts data that was originally encrypted using a raw + cryptographic mechanism. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_raw_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.RawDecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + initialization_vector=b'initialization_vector_blob', + ) + + # Make the request + response = client.raw_decrypt(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.RawDecryptRequest, dict]): + The request object. Request message for + [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.RawDecryptResponse: + Response message for + [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.RawDecryptRequest): + request = service.RawDecryptRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.raw_decrypt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def asymmetric_sign(self, + request: Optional[Union[service.AsymmetricSignRequest, dict]] = None, + *, + name: Optional[str] = None, + digest: Optional[service.Digest] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AsymmetricSignResponse: + r"""Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_SIGN, producing a signature that can be verified with + the public key retrieved from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_asymmetric_sign(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.AsymmetricSignRequest( + name="name_value", + ) + + # Make the request + response = client.asymmetric_sign(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.AsymmetricSignRequest, dict]): + The request object. Request message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for signing. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + digest (google.cloud.kms_v1.types.Digest): + Optional. The digest of the data to sign. The digest + must be produced with the same digest algorithm as + specified by the key version's + [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + + This field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. + + This corresponds to the ``digest`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.AsymmetricSignResponse: + Response message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, digest]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.AsymmetricSignRequest): + request = service.AsymmetricSignRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if digest is not None: + request.digest = digest + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.asymmetric_sign] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def asymmetric_decrypt(self, + request: Optional[Union[service.AsymmetricDecryptRequest, dict]] = None, + *, + name: Optional[str] = None, + ciphertext: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.AsymmetricDecryptResponse: + r"""Decrypts data that was encrypted with a public key retrieved + from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] + corresponding to a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_DECRYPT. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_asymmetric_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.AsymmetricDecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + ) + + # Make the request + response = client.asymmetric_decrypt(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.AsymmetricDecryptRequest, dict]): + The request object. Request message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for decryption. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ciphertext (bytes): + Required. The data encrypted with the named + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + public key using OAEP. + + This corresponds to the ``ciphertext`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.AsymmetricDecryptResponse: + Response message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, ciphertext]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.AsymmetricDecryptRequest): + request = service.AsymmetricDecryptRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ciphertext is not None: + request.ciphertext = ciphertext + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.asymmetric_decrypt] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def mac_sign(self, + request: Optional[Union[service.MacSignRequest, dict]] = None, + *, + name: Optional[str] = None, + data: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.MacSignResponse: + r"""Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + producing a tag that can be verified by another source with the + same key. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_mac_sign(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.MacSignRequest( + name="name_value", + data=b'data_blob', + ) + + # Make the request + response = client.mac_sign(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.MacSignRequest, dict]): + The request object. Request message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for signing. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (bytes): + Required. The data to sign. The MAC + tag is computed over this data field + based on the specific algorithm. + + This corresponds to the ``data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.MacSignResponse: + Response message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, data]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.MacSignRequest): + request = service.MacSignRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.mac_sign] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def mac_verify(self, + request: Optional[Union[service.MacVerifyRequest, dict]] = None, + *, + name: Optional[str] = None, + data: Optional[bytes] = None, + mac: Optional[bytes] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.MacVerifyResponse: + r"""Verifies MAC tag using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + and returns a response that indicates whether or not the + verification was successful. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import kms_v1 + + def sample_mac_verify(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.MacVerifyRequest( + name="name_value", + data=b'data_blob', + mac=b'mac_blob', + ) + + # Make the request + response = client.mac_verify(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.MacVerifyRequest, dict]): + The request object. Request message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + to use for verification. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + data (bytes): + Required. The data used previously as a + [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] + to generate the MAC tag. + + This corresponds to the ``data`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + mac (bytes): + Required. The signature to verify. + This corresponds to the ``mac`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.MacVerifyResponse: + Response message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + + """ + # Create or coerce a protobuf request object. + # - Quick 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, data, mac]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.MacVerifyRequest): + request = service.MacVerifyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if data is not None: + request.data = data + if mac is not None: + request.mac = mac + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.mac_verify] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("name", request.name), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def generate_random_bytes(self, + request: Optional[Union[service.GenerateRandomBytesRequest, dict]] = None, + *, + location: Optional[str] = None, + length_bytes: Optional[int] = None, + protection_level: Optional[resources.ProtectionLevel] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateRandomBytesResponse: + r"""Generate random bytes using the Cloud KMS randomness + source in the 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 import kms_v1 + + def sample_generate_random_bytes(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GenerateRandomBytesRequest( + ) + + # Make the request + response = client.generate_random_bytes(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.GenerateRandomBytesRequest, dict]): + The request object. Request message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + location (str): + The project-specific location in + which to generate random bytes. For + example, + "projects/my-project/locations/us-central1". + + This corresponds to the ``location`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + length_bytes (int): + The length in bytes of the amount of + randomness to retrieve. Minimum 8 + bytes, maximum 1024 bytes. + + This corresponds to the ``length_bytes`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + to use when generating the random data. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] + protection level is supported. + + This corresponds to the ``protection_level`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.kms_v1.types.GenerateRandomBytesResponse: + Response message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([location, length_bytes, protection_level]) + if request is not None and has_flattened_params: + raise ValueError('If the `request` argument is set, then none of ' + 'the individual field arguments should be set.') + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.GenerateRandomBytesRequest): + request = service.GenerateRandomBytesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if location is not None: + request.location = location + if length_bytes is not None: + request.length_bytes = length_bytes + if protection_level is not None: + request.protection_level = protection_level + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.generate_random_bytes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ("location", request.location), + )), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "KeyManagementServiceClient": + 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 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 = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_location] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_locations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Sets the IAM access control policy on the specified function. + + Replaces any existing policy. + + Args: + request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Gets the IAM access control policy for a function. + + Returns an empty policy if the function exists and does not have a + policy set. + + Args: + request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + retry (google.api_core.retry.Retry): Designation of what errors, if + any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.policy_pb2.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Tests the specified IAM permissions against the IAM access control + policy for a function. + + If the function does not exist, this will return an empty set + of permissions, not a NOT_FOUND error. + + Args: + request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy_pb2.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("resource", request.resource),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +__all__ = ( + "KeyManagementServiceClient", +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/pagers.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/pagers.py new file mode 100644 index 000000000000..efdfd7733d45 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/pagers.py @@ -0,0 +1,568 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async +from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.kms_v1.types import resources +from google.cloud.kms_v1.types import service + + +class ListKeyRingsPager: + """A pager for iterating through ``list_key_rings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``key_rings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListKeyRings`` requests and continue to iterate + through the ``key_rings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., service.ListKeyRingsResponse], + request: service.ListKeyRingsRequest, + response: service.ListKeyRingsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListKeyRingsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListKeyRingsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListKeyRingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListKeyRingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.KeyRing]: + for page in self.pages: + yield from page.key_rings + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListKeyRingsAsyncPager: + """A pager for iterating through ``list_key_rings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``key_rings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListKeyRings`` requests and continue to iterate + through the ``key_rings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[service.ListKeyRingsResponse]], + request: service.ListKeyRingsRequest, + response: service.ListKeyRingsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListKeyRingsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListKeyRingsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListKeyRingsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListKeyRingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.KeyRing]: + async def async_generator(): + async for page in self.pages: + for response in page.key_rings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCryptoKeysPager: + """A pager for iterating through ``list_crypto_keys`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` object, and + provides an ``__iter__`` method to iterate through its + ``crypto_keys`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCryptoKeys`` requests and continue to iterate + through the ``crypto_keys`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., service.ListCryptoKeysResponse], + request: service.ListCryptoKeysRequest, + response: service.ListCryptoKeysResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListCryptoKeysRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListCryptoKeysResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListCryptoKeysRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListCryptoKeysResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.CryptoKey]: + for page in self.pages: + yield from page.crypto_keys + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCryptoKeysAsyncPager: + """A pager for iterating through ``list_crypto_keys`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``crypto_keys`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCryptoKeys`` requests and continue to iterate + through the ``crypto_keys`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[service.ListCryptoKeysResponse]], + request: service.ListCryptoKeysRequest, + response: service.ListCryptoKeysResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListCryptoKeysRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListCryptoKeysResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListCryptoKeysRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListCryptoKeysResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.CryptoKey]: + async def async_generator(): + async for page in self.pages: + for response in page.crypto_keys: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCryptoKeyVersionsPager: + """A pager for iterating through ``list_crypto_key_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``crypto_key_versions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListCryptoKeyVersions`` requests and continue to iterate + through the ``crypto_key_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., service.ListCryptoKeyVersionsResponse], + request: service.ListCryptoKeyVersionsRequest, + response: service.ListCryptoKeyVersionsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListCryptoKeyVersionsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListCryptoKeyVersionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListCryptoKeyVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.CryptoKeyVersion]: + for page in self.pages: + yield from page.crypto_key_versions + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListCryptoKeyVersionsAsyncPager: + """A pager for iterating through ``list_crypto_key_versions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``crypto_key_versions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListCryptoKeyVersions`` requests and continue to iterate + through the ``crypto_key_versions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[service.ListCryptoKeyVersionsResponse]], + request: service.ListCryptoKeyVersionsRequest, + response: service.ListCryptoKeyVersionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListCryptoKeyVersionsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListCryptoKeyVersionsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListCryptoKeyVersionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.CryptoKeyVersion]: + async def async_generator(): + async for page in self.pages: + for response in page.crypto_key_versions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListImportJobsPager: + """A pager for iterating through ``list_import_jobs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListImportJobsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``import_jobs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListImportJobs`` requests and continue to iterate + through the ``import_jobs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListImportJobsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., service.ListImportJobsResponse], + request: service.ListImportJobsRequest, + response: service.ListImportJobsResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListImportJobsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListImportJobsResponse): + The initial response object. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListImportJobsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListImportJobsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[resources.ImportJob]: + for page in self.pages: + yield from page.import_jobs + + def __repr__(self) -> str: + return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) + + +class ListImportJobsAsyncPager: + """A pager for iterating through ``list_import_jobs`` requests. + + This class thinly wraps an initial + :class:`google.cloud.kms_v1.types.ListImportJobsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``import_jobs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListImportJobs`` requests and continue to iterate + through the ``import_jobs`` field on the + corresponding responses. + + All the usual :class:`google.cloud.kms_v1.types.ListImportJobsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + def __init__(self, + method: Callable[..., Awaitable[service.ListImportJobsResponse]], + request: service.ListImportJobsRequest, + response: service.ListImportJobsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + 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.kms_v1.types.ListImportJobsRequest): + The initial request object. + response (google.cloud.kms_v1.types.ListImportJobsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = service.ListImportJobsRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListImportJobsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) + yield self._response + def __aiter__(self) -> AsyncIterator[resources.ImportJob]: + async def async_generator(): + async for page in self.pages: + for response in page.import_jobs: + 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-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/README.rst b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/README.rst new file mode 100644 index 000000000000..ebe015054ce3 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`KeyManagementServiceTransport` is the ABC for all transports. +- public child `KeyManagementServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `KeyManagementServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseKeyManagementServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `KeyManagementServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py new file mode 100644 index 000000000000..d2742fe4c9e0 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import KeyManagementServiceTransport +from .grpc import KeyManagementServiceGrpcTransport +from .grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport +from .rest import KeyManagementServiceRestTransport +from .rest import KeyManagementServiceRestInterceptor + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[KeyManagementServiceTransport]] +_transport_registry['grpc'] = KeyManagementServiceGrpcTransport +_transport_registry['grpc_asyncio'] = KeyManagementServiceGrpcAsyncIOTransport +_transport_registry['rest'] = KeyManagementServiceRestTransport + +__all__ = ( + 'KeyManagementServiceTransport', + 'KeyManagementServiceGrpcTransport', + 'KeyManagementServiceGrpcAsyncIOTransport', + 'KeyManagementServiceRestTransport', + 'KeyManagementServiceRestInterceptor', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py new file mode 100644 index 000000000000..dbfd1ea5078b --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py @@ -0,0 +1,863 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +from google.cloud.kms_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.kms_v1.types import resources +from google.cloud.kms_v1.types import service +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) + + +class KeyManagementServiceTransport(abc.ABC): + """Abstract transport class for KeyManagementService.""" + + AUTH_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', + ) + + DEFAULT_HOST: str = 'cloudkms.googleapis.com' + def __init__( + self, *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, + **scopes_kwargs, + quota_project_id=quota_project_id + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience(api_audience if api_audience else host) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ':' not in host: + host += ':443' + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_key_rings: gapic_v1.method.wrap_method( + self.list_key_rings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_crypto_keys: gapic_v1.method.wrap_method( + self.list_crypto_keys, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_crypto_key_versions: gapic_v1.method.wrap_method( + self.list_crypto_key_versions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_import_jobs: gapic_v1.method.wrap_method( + self.list_import_jobs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_key_ring: gapic_v1.method.wrap_method( + self.get_key_ring, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_crypto_key: gapic_v1.method.wrap_method( + self.get_crypto_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_crypto_key_version: gapic_v1.method.wrap_method( + self.get_crypto_key_version, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_public_key: gapic_v1.method.wrap_method( + self.get_public_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_import_job: gapic_v1.method.wrap_method( + self.get_import_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_key_ring: gapic_v1.method.wrap_method( + self.create_key_ring, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_crypto_key: gapic_v1.method.wrap_method( + self.create_crypto_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_crypto_key_version: gapic_v1.method.wrap_method( + self.create_crypto_key_version, + default_timeout=60.0, + client_info=client_info, + ), + self.import_crypto_key_version: gapic_v1.method.wrap_method( + self.import_crypto_key_version, + default_timeout=60.0, + client_info=client_info, + ), + self.create_import_job: gapic_v1.method.wrap_method( + self.create_import_job, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_crypto_key: gapic_v1.method.wrap_method( + self.update_crypto_key, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_crypto_key_version: gapic_v1.method.wrap_method( + self.update_crypto_key_version, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_crypto_key_primary_version: gapic_v1.method.wrap_method( + self.update_crypto_key_primary_version, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.destroy_crypto_key_version: gapic_v1.method.wrap_method( + self.destroy_crypto_key_version, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.restore_crypto_key_version: gapic_v1.method.wrap_method( + self.restore_crypto_key_version, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.encrypt: gapic_v1.method.wrap_method( + self.encrypt, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.decrypt: gapic_v1.method.wrap_method( + self.decrypt, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.raw_encrypt: gapic_v1.method.wrap_method( + self.raw_encrypt, + default_timeout=None, + client_info=client_info, + ), + self.raw_decrypt: gapic_v1.method.wrap_method( + self.raw_decrypt, + default_timeout=None, + client_info=client_info, + ), + self.asymmetric_sign: gapic_v1.method.wrap_method( + self.asymmetric_sign, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.asymmetric_decrypt: gapic_v1.method.wrap_method( + self.asymmetric_decrypt, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.mac_sign: gapic_v1.method.wrap_method( + self.mac_sign, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.mac_verify: gapic_v1.method.wrap_method( + self.mac_verify, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_random_bytes: gapic_v1.method.wrap_method( + self.generate_random_bytes, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_location: gapic_v1.method.wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: gapic_v1.method.wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + 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_key_rings(self) -> Callable[ + [service.ListKeyRingsRequest], + Union[ + service.ListKeyRingsResponse, + Awaitable[service.ListKeyRingsResponse] + ]]: + raise NotImplementedError() + + @property + def list_crypto_keys(self) -> Callable[ + [service.ListCryptoKeysRequest], + Union[ + service.ListCryptoKeysResponse, + Awaitable[service.ListCryptoKeysResponse] + ]]: + raise NotImplementedError() + + @property + def list_crypto_key_versions(self) -> Callable[ + [service.ListCryptoKeyVersionsRequest], + Union[ + service.ListCryptoKeyVersionsResponse, + Awaitable[service.ListCryptoKeyVersionsResponse] + ]]: + raise NotImplementedError() + + @property + def list_import_jobs(self) -> Callable[ + [service.ListImportJobsRequest], + Union[ + service.ListImportJobsResponse, + Awaitable[service.ListImportJobsResponse] + ]]: + raise NotImplementedError() + + @property + def get_key_ring(self) -> Callable[ + [service.GetKeyRingRequest], + Union[ + resources.KeyRing, + Awaitable[resources.KeyRing] + ]]: + raise NotImplementedError() + + @property + def get_crypto_key(self) -> Callable[ + [service.GetCryptoKeyRequest], + Union[ + resources.CryptoKey, + Awaitable[resources.CryptoKey] + ]]: + raise NotImplementedError() + + @property + def get_crypto_key_version(self) -> Callable[ + [service.GetCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def get_public_key(self) -> Callable[ + [service.GetPublicKeyRequest], + Union[ + resources.PublicKey, + Awaitable[resources.PublicKey] + ]]: + raise NotImplementedError() + + @property + def get_import_job(self) -> Callable[ + [service.GetImportJobRequest], + Union[ + resources.ImportJob, + Awaitable[resources.ImportJob] + ]]: + raise NotImplementedError() + + @property + def create_key_ring(self) -> Callable[ + [service.CreateKeyRingRequest], + Union[ + resources.KeyRing, + Awaitable[resources.KeyRing] + ]]: + raise NotImplementedError() + + @property + def create_crypto_key(self) -> Callable[ + [service.CreateCryptoKeyRequest], + Union[ + resources.CryptoKey, + Awaitable[resources.CryptoKey] + ]]: + raise NotImplementedError() + + @property + def create_crypto_key_version(self) -> Callable[ + [service.CreateCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def import_crypto_key_version(self) -> Callable[ + [service.ImportCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def create_import_job(self) -> Callable[ + [service.CreateImportJobRequest], + Union[ + resources.ImportJob, + Awaitable[resources.ImportJob] + ]]: + raise NotImplementedError() + + @property + def update_crypto_key(self) -> Callable[ + [service.UpdateCryptoKeyRequest], + Union[ + resources.CryptoKey, + Awaitable[resources.CryptoKey] + ]]: + raise NotImplementedError() + + @property + def update_crypto_key_version(self) -> Callable[ + [service.UpdateCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def update_crypto_key_primary_version(self) -> Callable[ + [service.UpdateCryptoKeyPrimaryVersionRequest], + Union[ + resources.CryptoKey, + Awaitable[resources.CryptoKey] + ]]: + raise NotImplementedError() + + @property + def destroy_crypto_key_version(self) -> Callable[ + [service.DestroyCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def restore_crypto_key_version(self) -> Callable[ + [service.RestoreCryptoKeyVersionRequest], + Union[ + resources.CryptoKeyVersion, + Awaitable[resources.CryptoKeyVersion] + ]]: + raise NotImplementedError() + + @property + def encrypt(self) -> Callable[ + [service.EncryptRequest], + Union[ + service.EncryptResponse, + Awaitable[service.EncryptResponse] + ]]: + raise NotImplementedError() + + @property + def decrypt(self) -> Callable[ + [service.DecryptRequest], + Union[ + service.DecryptResponse, + Awaitable[service.DecryptResponse] + ]]: + raise NotImplementedError() + + @property + def raw_encrypt(self) -> Callable[ + [service.RawEncryptRequest], + Union[ + service.RawEncryptResponse, + Awaitable[service.RawEncryptResponse] + ]]: + raise NotImplementedError() + + @property + def raw_decrypt(self) -> Callable[ + [service.RawDecryptRequest], + Union[ + service.RawDecryptResponse, + Awaitable[service.RawDecryptResponse] + ]]: + raise NotImplementedError() + + @property + def asymmetric_sign(self) -> Callable[ + [service.AsymmetricSignRequest], + Union[ + service.AsymmetricSignResponse, + Awaitable[service.AsymmetricSignResponse] + ]]: + raise NotImplementedError() + + @property + def asymmetric_decrypt(self) -> Callable[ + [service.AsymmetricDecryptRequest], + Union[ + service.AsymmetricDecryptResponse, + Awaitable[service.AsymmetricDecryptResponse] + ]]: + raise NotImplementedError() + + @property + def mac_sign(self) -> Callable[ + [service.MacSignRequest], + Union[ + service.MacSignResponse, + Awaitable[service.MacSignResponse] + ]]: + raise NotImplementedError() + + @property + def mac_verify(self) -> Callable[ + [service.MacVerifyRequest], + Union[ + service.MacVerifyResponse, + Awaitable[service.MacVerifyResponse] + ]]: + raise NotImplementedError() + + @property + def generate_random_bytes(self) -> Callable[ + [service.GenerateRandomBytesRequest], + Union[ + service.GenerateRandomBytesResponse, + Awaitable[service.GenerateRandomBytesResponse] + ]]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_location(self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations(self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ( + 'KeyManagementServiceTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py new file mode 100644 index 000000000000..e27f19fbadb8 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py @@ -0,0 +1,1250 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.kms_v1.types import resources +from google.cloud.kms_v1.types import service +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO + + +class KeyManagementServiceGrpcTransport(KeyManagementServiceTransport): + """gRPC backend transport for KeyManagementService. + + Google Cloud Key Management Service + + Manages cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [KeyRing][google.cloud.kms.v1.KeyRing] + - [CryptoKey][google.cloud.kms.v1.CryptoKey] + - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + - [ImportJob][google.cloud.kms.v1.ImportJob] + + If you are using manual gRPC libraries, see `Using gRPC with Cloud + KMS `__. + + 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 = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel(cls, + host: str = 'cloudkms.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_key_rings(self) -> Callable[ + [service.ListKeyRingsRequest], + service.ListKeyRingsResponse]: + r"""Return a callable for the list key rings method over gRPC. + + Lists [KeyRings][google.cloud.kms.v1.KeyRing]. + + Returns: + Callable[[~.ListKeyRingsRequest], + ~.ListKeyRingsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_rings' not in self._stubs: + self._stubs['list_key_rings'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListKeyRings', + request_serializer=service.ListKeyRingsRequest.serialize, + response_deserializer=service.ListKeyRingsResponse.deserialize, + ) + return self._stubs['list_key_rings'] + + @property + def list_crypto_keys(self) -> Callable[ + [service.ListCryptoKeysRequest], + service.ListCryptoKeysResponse]: + r"""Return a callable for the list crypto keys method over gRPC. + + Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.ListCryptoKeysRequest], + ~.ListCryptoKeysResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_keys' not in self._stubs: + self._stubs['list_crypto_keys'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeys', + request_serializer=service.ListCryptoKeysRequest.serialize, + response_deserializer=service.ListCryptoKeysResponse.deserialize, + ) + return self._stubs['list_crypto_keys'] + + @property + def list_crypto_key_versions(self) -> Callable[ + [service.ListCryptoKeyVersionsRequest], + service.ListCryptoKeyVersionsResponse]: + r"""Return a callable for the list crypto key versions method over gRPC. + + Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.ListCryptoKeyVersionsRequest], + ~.ListCryptoKeyVersionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key_versions' not in self._stubs: + self._stubs['list_crypto_key_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeyVersions', + request_serializer=service.ListCryptoKeyVersionsRequest.serialize, + response_deserializer=service.ListCryptoKeyVersionsResponse.deserialize, + ) + return self._stubs['list_crypto_key_versions'] + + @property + def list_import_jobs(self) -> Callable[ + [service.ListImportJobsRequest], + service.ListImportJobsResponse]: + r"""Return a callable for the list import jobs method over gRPC. + + Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. + + Returns: + Callable[[~.ListImportJobsRequest], + ~.ListImportJobsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_import_jobs' not in self._stubs: + self._stubs['list_import_jobs'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListImportJobs', + request_serializer=service.ListImportJobsRequest.serialize, + response_deserializer=service.ListImportJobsResponse.deserialize, + ) + return self._stubs['list_import_jobs'] + + @property + def get_key_ring(self) -> Callable[ + [service.GetKeyRingRequest], + resources.KeyRing]: + r"""Return a callable for the get key ring method over gRPC. + + Returns metadata for a given + [KeyRing][google.cloud.kms.v1.KeyRing]. + + Returns: + Callable[[~.GetKeyRingRequest], + ~.KeyRing]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_ring' not in self._stubs: + self._stubs['get_key_ring'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetKeyRing', + request_serializer=service.GetKeyRingRequest.serialize, + response_deserializer=resources.KeyRing.deserialize, + ) + return self._stubs['get_key_ring'] + + @property + def get_crypto_key(self) -> Callable[ + [service.GetCryptoKeyRequest], + resources.CryptoKey]: + r"""Return a callable for the get crypto key method over gRPC. + + Returns metadata for a given + [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its + [primary][google.cloud.kms.v1.CryptoKey.primary] + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.GetCryptoKeyRequest], + ~.CryptoKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: + self._stubs['get_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetCryptoKey', + request_serializer=service.GetCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['get_crypto_key'] + + @property + def get_crypto_key_version(self) -> Callable[ + [service.GetCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the get crypto key version method over gRPC. + + Returns metadata for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.GetCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: + self._stubs['get_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetCryptoKeyVersion', + request_serializer=service.GetCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['get_crypto_key_version'] + + @property + def get_public_key(self) -> Callable[ + [service.GetPublicKeyRequest], + resources.PublicKey]: + r"""Return a callable for the get public key method over gRPC. + + Returns the public key for the given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] + or + [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. + + Returns: + Callable[[~.GetPublicKeyRequest], + ~.PublicKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_public_key' not in self._stubs: + self._stubs['get_public_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetPublicKey', + request_serializer=service.GetPublicKeyRequest.serialize, + response_deserializer=resources.PublicKey.deserialize, + ) + return self._stubs['get_public_key'] + + @property + def get_import_job(self) -> Callable[ + [service.GetImportJobRequest], + resources.ImportJob]: + r"""Return a callable for the get import job method over gRPC. + + Returns metadata for a given + [ImportJob][google.cloud.kms.v1.ImportJob]. + + Returns: + Callable[[~.GetImportJobRequest], + ~.ImportJob]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_import_job' not in self._stubs: + self._stubs['get_import_job'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetImportJob', + request_serializer=service.GetImportJobRequest.serialize, + response_deserializer=resources.ImportJob.deserialize, + ) + return self._stubs['get_import_job'] + + @property + def create_key_ring(self) -> Callable[ + [service.CreateKeyRingRequest], + resources.KeyRing]: + r"""Return a callable for the create key ring method over gRPC. + + Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given + Project and Location. + + Returns: + Callable[[~.CreateKeyRingRequest], + ~.KeyRing]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_ring' not in self._stubs: + self._stubs['create_key_ring'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateKeyRing', + request_serializer=service.CreateKeyRingRequest.serialize, + response_deserializer=resources.KeyRing.deserialize, + ) + return self._stubs['create_key_ring'] + + @property + def create_crypto_key(self) -> Callable[ + [service.CreateCryptoKeyRequest], + resources.CryptoKey]: + r"""Return a callable for the create crypto key method over gRPC. + + Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and + [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] + are required. + + Returns: + Callable[[~.CreateCryptoKeyRequest], + ~.CryptoKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: + self._stubs['create_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKey', + request_serializer=service.CreateCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['create_crypto_key'] + + @property + def create_crypto_key_version(self) -> Callable[ + [service.CreateCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the create crypto key version method over gRPC. + + Create a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The server will assign the next sequential id. If unset, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. + + Returns: + Callable[[~.CreateCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: + self._stubs['create_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKeyVersion', + request_serializer=service.CreateCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['create_crypto_key_version'] + + @property + def import_crypto_key_version(self) -> Callable[ + [service.ImportCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the import crypto key version method over gRPC. + + Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.ImportCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_crypto_key_version' not in self._stubs: + self._stubs['import_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ImportCryptoKeyVersion', + request_serializer=service.ImportCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['import_crypto_key_version'] + + @property + def create_import_job(self) -> Callable[ + [service.CreateImportJobRequest], + resources.ImportJob]: + r"""Return a callable for the create import job method over gRPC. + + Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] + is required. + + Returns: + Callable[[~.CreateImportJobRequest], + ~.ImportJob]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_import_job' not in self._stubs: + self._stubs['create_import_job'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateImportJob', + request_serializer=service.CreateImportJobRequest.serialize, + response_deserializer=resources.ImportJob.deserialize, + ) + return self._stubs['create_import_job'] + + @property + def update_crypto_key(self) -> Callable[ + [service.UpdateCryptoKeyRequest], + resources.CryptoKey]: + r"""Return a callable for the update crypto key method over gRPC. + + Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.UpdateCryptoKeyRequest], + ~.CryptoKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: + self._stubs['update_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKey', + request_serializer=service.UpdateCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['update_crypto_key'] + + @property + def update_crypto_key_version(self) -> Callable[ + [service.UpdateCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the update crypto key version method over gRPC. + + Update a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + metadata. + + [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be + changed between + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + and + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] + using this method. See + [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] + and + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + to move between other states. + + Returns: + Callable[[~.UpdateCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: + self._stubs['update_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyVersion', + request_serializer=service.UpdateCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['update_crypto_key_version'] + + @property + def update_crypto_key_primary_version(self) -> Callable[ + [service.UpdateCryptoKeyPrimaryVersionRequest], + resources.CryptoKey]: + r"""Return a callable for the update crypto key primary + version method over gRPC. + + Update the version of a + [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Returns an error if called on a key whose purpose is not + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.UpdateCryptoKeyPrimaryVersionRequest], + ~.CryptoKey]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key_primary_version' not in self._stubs: + self._stubs['update_crypto_key_primary_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyPrimaryVersion', + request_serializer=service.UpdateCryptoKeyPrimaryVersionRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['update_crypto_key_primary_version'] + + @property + def destroy_crypto_key_version(self) -> Callable[ + [service.DestroyCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the destroy crypto key version method over gRPC. + + Schedule a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for + destruction. + + Upon calling this method, + [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] + will be set to + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be set to the time + [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] + in the future. At that time, the + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will + automatically change to + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], + and the key material will be irrevocably destroyed. + + Before the + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + is reached, + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + may be called to reverse the process. + + Returns: + Callable[[~.DestroyCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'destroy_crypto_key_version' not in self._stubs: + self._stubs['destroy_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/DestroyCryptoKeyVersion', + request_serializer=service.DestroyCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['destroy_crypto_key_version'] + + @property + def restore_crypto_key_version(self) -> Callable[ + [service.RestoreCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + r"""Return a callable for the restore crypto key version method over gRPC. + + Restore a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] + state. + + Upon restoration of the CryptoKeyVersion, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be cleared. + + Returns: + Callable[[~.RestoreCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_crypto_key_version' not in self._stubs: + self._stubs['restore_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/RestoreCryptoKeyVersion', + request_serializer=service.RestoreCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['restore_crypto_key_version'] + + @property + def encrypt(self) -> Callable[ + [service.EncryptRequest], + service.EncryptResponse]: + r"""Return a callable for the encrypt method over gRPC. + + Encrypts data, so that it can only be recovered by a call to + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.EncryptRequest], + ~.EncryptResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'encrypt' not in self._stubs: + self._stubs['encrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/Encrypt', + request_serializer=service.EncryptRequest.serialize, + response_deserializer=service.EncryptResponse.deserialize, + ) + return self._stubs['encrypt'] + + @property + def decrypt(self) -> Callable[ + [service.DecryptRequest], + service.DecryptResponse]: + r"""Return a callable for the decrypt method over gRPC. + + Decrypts data that was protected by + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.DecryptRequest], + ~.DecryptResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'decrypt' not in self._stubs: + self._stubs['decrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/Decrypt', + request_serializer=service.DecryptRequest.serialize, + response_deserializer=service.DecryptResponse.deserialize, + ) + return self._stubs['decrypt'] + + @property + def raw_encrypt(self) -> Callable[ + [service.RawEncryptRequest], + service.RawEncryptResponse]: + r"""Return a callable for the raw encrypt method over gRPC. + + Encrypts data using portable cryptographic primitives. Most + users should choose + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] and + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt] + rather than their raw counterparts. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.RawEncryptRequest], + ~.RawEncryptResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'raw_encrypt' not in self._stubs: + self._stubs['raw_encrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/RawEncrypt', + request_serializer=service.RawEncryptRequest.serialize, + response_deserializer=service.RawEncryptResponse.deserialize, + ) + return self._stubs['raw_encrypt'] + + @property + def raw_decrypt(self) -> Callable[ + [service.RawDecryptRequest], + service.RawDecryptResponse]: + r"""Return a callable for the raw decrypt method over gRPC. + + Decrypts data that was originally encrypted using a raw + cryptographic mechanism. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.RawDecryptRequest], + ~.RawDecryptResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'raw_decrypt' not in self._stubs: + self._stubs['raw_decrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/RawDecrypt', + request_serializer=service.RawDecryptRequest.serialize, + response_deserializer=service.RawDecryptResponse.deserialize, + ) + return self._stubs['raw_decrypt'] + + @property + def asymmetric_sign(self) -> Callable[ + [service.AsymmetricSignRequest], + service.AsymmetricSignResponse]: + r"""Return a callable for the asymmetric sign method over gRPC. + + Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_SIGN, producing a signature that can be verified with + the public key retrieved from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + Returns: + Callable[[~.AsymmetricSignRequest], + ~.AsymmetricSignResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'asymmetric_sign' not in self._stubs: + self._stubs['asymmetric_sign'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/AsymmetricSign', + request_serializer=service.AsymmetricSignRequest.serialize, + response_deserializer=service.AsymmetricSignResponse.deserialize, + ) + return self._stubs['asymmetric_sign'] + + @property + def asymmetric_decrypt(self) -> Callable[ + [service.AsymmetricDecryptRequest], + service.AsymmetricDecryptResponse]: + r"""Return a callable for the asymmetric decrypt method over gRPC. + + Decrypts data that was encrypted with a public key retrieved + from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] + corresponding to a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_DECRYPT. + + Returns: + Callable[[~.AsymmetricDecryptRequest], + ~.AsymmetricDecryptResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'asymmetric_decrypt' not in self._stubs: + self._stubs['asymmetric_decrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/AsymmetricDecrypt', + request_serializer=service.AsymmetricDecryptRequest.serialize, + response_deserializer=service.AsymmetricDecryptResponse.deserialize, + ) + return self._stubs['asymmetric_decrypt'] + + @property + def mac_sign(self) -> Callable[ + [service.MacSignRequest], + service.MacSignResponse]: + r"""Return a callable for the mac sign method over gRPC. + + Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + producing a tag that can be verified by another source with the + same key. + + Returns: + Callable[[~.MacSignRequest], + ~.MacSignResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'mac_sign' not in self._stubs: + self._stubs['mac_sign'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/MacSign', + request_serializer=service.MacSignRequest.serialize, + response_deserializer=service.MacSignResponse.deserialize, + ) + return self._stubs['mac_sign'] + + @property + def mac_verify(self) -> Callable[ + [service.MacVerifyRequest], + service.MacVerifyResponse]: + r"""Return a callable for the mac verify method over gRPC. + + Verifies MAC tag using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + and returns a response that indicates whether or not the + verification was successful. + + Returns: + Callable[[~.MacVerifyRequest], + ~.MacVerifyResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'mac_verify' not in self._stubs: + self._stubs['mac_verify'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/MacVerify', + request_serializer=service.MacVerifyRequest.serialize, + response_deserializer=service.MacVerifyResponse.deserialize, + ) + return self._stubs['mac_verify'] + + @property + def generate_random_bytes(self) -> Callable[ + [service.GenerateRandomBytesRequest], + service.GenerateRandomBytesResponse]: + r"""Return a callable for the generate random bytes method over gRPC. + + Generate random bytes using the Cloud KMS randomness + source in the provided location. + + Returns: + Callable[[~.GenerateRandomBytesRequest], + ~.GenerateRandomBytesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_random_bytes' not in self._stubs: + self._stubs['generate_random_bytes'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GenerateRandomBytes', + request_serializer=service.GenerateRandomBytesRequest.serialize, + response_deserializer=service.GenerateRandomBytesResponse.deserialize, + ) + return self._stubs['generate_random_bytes'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def close(self): + self.grpc_channel.close() + + @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_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ( + 'KeyManagementServiceGrpcTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..dc7465ff0077 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py @@ -0,0 +1,1677 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import inspect +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async +from google.api_core import exceptions as core_exceptions +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.kms_v1.types import resources +from google.cloud.kms_v1.types import service +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from .base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import KeyManagementServiceGrpcTransport + + +class KeyManagementServiceGrpcAsyncIOTransport(KeyManagementServiceTransport): + """gRPC AsyncIO backend transport for KeyManagementService. + + Google Cloud Key Management Service + + Manages cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [KeyRing][google.cloud.kms.v1.KeyRing] + - [CryptoKey][google.cloud.kms.v1.CryptoKey] + - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + - [ImportJob][google.cloud.kms.v1.ImportJob] + + If you are using manual gRPC libraries, see `Using gRPC with Cloud + KMS `__. + + 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 = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs + ) + + def __init__(self, *, + host: str = 'cloudkms.googleapis.com', + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + 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_key_rings(self) -> Callable[ + [service.ListKeyRingsRequest], + Awaitable[service.ListKeyRingsResponse]]: + r"""Return a callable for the list key rings method over gRPC. + + Lists [KeyRings][google.cloud.kms.v1.KeyRing]. + + Returns: + Callable[[~.ListKeyRingsRequest], + Awaitable[~.ListKeyRingsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_rings' not in self._stubs: + self._stubs['list_key_rings'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListKeyRings', + request_serializer=service.ListKeyRingsRequest.serialize, + response_deserializer=service.ListKeyRingsResponse.deserialize, + ) + return self._stubs['list_key_rings'] + + @property + def list_crypto_keys(self) -> Callable[ + [service.ListCryptoKeysRequest], + Awaitable[service.ListCryptoKeysResponse]]: + r"""Return a callable for the list crypto keys method over gRPC. + + Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.ListCryptoKeysRequest], + Awaitable[~.ListCryptoKeysResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_keys' not in self._stubs: + self._stubs['list_crypto_keys'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeys', + request_serializer=service.ListCryptoKeysRequest.serialize, + response_deserializer=service.ListCryptoKeysResponse.deserialize, + ) + return self._stubs['list_crypto_keys'] + + @property + def list_crypto_key_versions(self) -> Callable[ + [service.ListCryptoKeyVersionsRequest], + Awaitable[service.ListCryptoKeyVersionsResponse]]: + r"""Return a callable for the list crypto key versions method over gRPC. + + Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.ListCryptoKeyVersionsRequest], + Awaitable[~.ListCryptoKeyVersionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key_versions' not in self._stubs: + self._stubs['list_crypto_key_versions'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeyVersions', + request_serializer=service.ListCryptoKeyVersionsRequest.serialize, + response_deserializer=service.ListCryptoKeyVersionsResponse.deserialize, + ) + return self._stubs['list_crypto_key_versions'] + + @property + def list_import_jobs(self) -> Callable[ + [service.ListImportJobsRequest], + Awaitable[service.ListImportJobsResponse]]: + r"""Return a callable for the list import jobs method over gRPC. + + Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. + + Returns: + Callable[[~.ListImportJobsRequest], + Awaitable[~.ListImportJobsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_import_jobs' not in self._stubs: + self._stubs['list_import_jobs'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ListImportJobs', + request_serializer=service.ListImportJobsRequest.serialize, + response_deserializer=service.ListImportJobsResponse.deserialize, + ) + return self._stubs['list_import_jobs'] + + @property + def get_key_ring(self) -> Callable[ + [service.GetKeyRingRequest], + Awaitable[resources.KeyRing]]: + r"""Return a callable for the get key ring method over gRPC. + + Returns metadata for a given + [KeyRing][google.cloud.kms.v1.KeyRing]. + + Returns: + Callable[[~.GetKeyRingRequest], + Awaitable[~.KeyRing]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_ring' not in self._stubs: + self._stubs['get_key_ring'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetKeyRing', + request_serializer=service.GetKeyRingRequest.serialize, + response_deserializer=resources.KeyRing.deserialize, + ) + return self._stubs['get_key_ring'] + + @property + def get_crypto_key(self) -> Callable[ + [service.GetCryptoKeyRequest], + Awaitable[resources.CryptoKey]]: + r"""Return a callable for the get crypto key method over gRPC. + + Returns metadata for a given + [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its + [primary][google.cloud.kms.v1.CryptoKey.primary] + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.GetCryptoKeyRequest], + Awaitable[~.CryptoKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: + self._stubs['get_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetCryptoKey', + request_serializer=service.GetCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['get_crypto_key'] + + @property + def get_crypto_key_version(self) -> Callable[ + [service.GetCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the get crypto key version method over gRPC. + + Returns metadata for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + Returns: + Callable[[~.GetCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: + self._stubs['get_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetCryptoKeyVersion', + request_serializer=service.GetCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['get_crypto_key_version'] + + @property + def get_public_key(self) -> Callable[ + [service.GetPublicKeyRequest], + Awaitable[resources.PublicKey]]: + r"""Return a callable for the get public key method over gRPC. + + Returns the public key for the given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] + or + [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. + + Returns: + Callable[[~.GetPublicKeyRequest], + Awaitable[~.PublicKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_public_key' not in self._stubs: + self._stubs['get_public_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetPublicKey', + request_serializer=service.GetPublicKeyRequest.serialize, + response_deserializer=resources.PublicKey.deserialize, + ) + return self._stubs['get_public_key'] + + @property + def get_import_job(self) -> Callable[ + [service.GetImportJobRequest], + Awaitable[resources.ImportJob]]: + r"""Return a callable for the get import job method over gRPC. + + Returns metadata for a given + [ImportJob][google.cloud.kms.v1.ImportJob]. + + Returns: + Callable[[~.GetImportJobRequest], + Awaitable[~.ImportJob]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_import_job' not in self._stubs: + self._stubs['get_import_job'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GetImportJob', + request_serializer=service.GetImportJobRequest.serialize, + response_deserializer=resources.ImportJob.deserialize, + ) + return self._stubs['get_import_job'] + + @property + def create_key_ring(self) -> Callable[ + [service.CreateKeyRingRequest], + Awaitable[resources.KeyRing]]: + r"""Return a callable for the create key ring method over gRPC. + + Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given + Project and Location. + + Returns: + Callable[[~.CreateKeyRingRequest], + Awaitable[~.KeyRing]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_key_ring' not in self._stubs: + self._stubs['create_key_ring'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateKeyRing', + request_serializer=service.CreateKeyRingRequest.serialize, + response_deserializer=resources.KeyRing.deserialize, + ) + return self._stubs['create_key_ring'] + + @property + def create_crypto_key(self) -> Callable[ + [service.CreateCryptoKeyRequest], + Awaitable[resources.CryptoKey]]: + r"""Return a callable for the create crypto key method over gRPC. + + Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and + [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] + are required. + + Returns: + Callable[[~.CreateCryptoKeyRequest], + Awaitable[~.CryptoKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: + self._stubs['create_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKey', + request_serializer=service.CreateCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['create_crypto_key'] + + @property + def create_crypto_key_version(self) -> Callable[ + [service.CreateCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the create crypto key version method over gRPC. + + Create a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The server will assign the next sequential id. If unset, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. + + Returns: + Callable[[~.CreateCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: + self._stubs['create_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKeyVersion', + request_serializer=service.CreateCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['create_crypto_key_version'] + + @property + def import_crypto_key_version(self) -> Callable[ + [service.ImportCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the import crypto key version method over gRPC. + + Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.ImportCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'import_crypto_key_version' not in self._stubs: + self._stubs['import_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/ImportCryptoKeyVersion', + request_serializer=service.ImportCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['import_crypto_key_version'] + + @property + def create_import_job(self) -> Callable[ + [service.CreateImportJobRequest], + Awaitable[resources.ImportJob]]: + r"""Return a callable for the create import job method over gRPC. + + Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a + [KeyRing][google.cloud.kms.v1.KeyRing]. + + [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] + is required. + + Returns: + Callable[[~.CreateImportJobRequest], + Awaitable[~.ImportJob]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_import_job' not in self._stubs: + self._stubs['create_import_job'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/CreateImportJob', + request_serializer=service.CreateImportJobRequest.serialize, + response_deserializer=resources.ImportJob.deserialize, + ) + return self._stubs['create_import_job'] + + @property + def update_crypto_key(self) -> Callable[ + [service.UpdateCryptoKeyRequest], + Awaitable[resources.CryptoKey]]: + r"""Return a callable for the update crypto key method over gRPC. + + Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Returns: + Callable[[~.UpdateCryptoKeyRequest], + Awaitable[~.CryptoKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: + self._stubs['update_crypto_key'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKey', + request_serializer=service.UpdateCryptoKeyRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['update_crypto_key'] + + @property + def update_crypto_key_version(self) -> Callable[ + [service.UpdateCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the update crypto key version method over gRPC. + + Update a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + metadata. + + [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be + changed between + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + and + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] + using this method. See + [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] + and + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + to move between other states. + + Returns: + Callable[[~.UpdateCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: + self._stubs['update_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyVersion', + request_serializer=service.UpdateCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['update_crypto_key_version'] + + @property + def update_crypto_key_primary_version(self) -> Callable[ + [service.UpdateCryptoKeyPrimaryVersionRequest], + Awaitable[resources.CryptoKey]]: + r"""Return a callable for the update crypto key primary + version method over gRPC. + + Update the version of a + [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Returns an error if called on a key whose purpose is not + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.UpdateCryptoKeyPrimaryVersionRequest], + Awaitable[~.CryptoKey]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-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_crypto_key_primary_version' not in self._stubs: + self._stubs['update_crypto_key_primary_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyPrimaryVersion', + request_serializer=service.UpdateCryptoKeyPrimaryVersionRequest.serialize, + response_deserializer=resources.CryptoKey.deserialize, + ) + return self._stubs['update_crypto_key_primary_version'] + + @property + def destroy_crypto_key_version(self) -> Callable[ + [service.DestroyCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the destroy crypto key version method over gRPC. + + Schedule a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for + destruction. + + Upon calling this method, + [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] + will be set to + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be set to the time + [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] + in the future. At that time, the + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will + automatically change to + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], + and the key material will be irrevocably destroyed. + + Before the + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + is reached, + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + may be called to reverse the process. + + Returns: + Callable[[~.DestroyCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'destroy_crypto_key_version' not in self._stubs: + self._stubs['destroy_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/DestroyCryptoKeyVersion', + request_serializer=service.DestroyCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['destroy_crypto_key_version'] + + @property + def restore_crypto_key_version(self) -> Callable[ + [service.RestoreCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion]]: + r"""Return a callable for the restore crypto key version method over gRPC. + + Restore a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] + state. + + Upon restoration of the CryptoKeyVersion, + [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set + to + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], + and + [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] + will be cleared. + + Returns: + Callable[[~.RestoreCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'restore_crypto_key_version' not in self._stubs: + self._stubs['restore_crypto_key_version'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/RestoreCryptoKeyVersion', + request_serializer=service.RestoreCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + return self._stubs['restore_crypto_key_version'] + + @property + def encrypt(self) -> Callable[ + [service.EncryptRequest], + Awaitable[service.EncryptResponse]]: + r"""Return a callable for the encrypt method over gRPC. + + Encrypts data, so that it can only be recovered by a call to + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.EncryptRequest], + Awaitable[~.EncryptResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'encrypt' not in self._stubs: + self._stubs['encrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/Encrypt', + request_serializer=service.EncryptRequest.serialize, + response_deserializer=service.EncryptResponse.deserialize, + ) + return self._stubs['encrypt'] + + @property + def decrypt(self) -> Callable[ + [service.DecryptRequest], + Awaitable[service.DecryptResponse]]: + r"""Return a callable for the decrypt method over gRPC. + + Decrypts data that was protected by + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.DecryptRequest], + Awaitable[~.DecryptResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'decrypt' not in self._stubs: + self._stubs['decrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/Decrypt', + request_serializer=service.DecryptRequest.serialize, + response_deserializer=service.DecryptResponse.deserialize, + ) + return self._stubs['decrypt'] + + @property + def raw_encrypt(self) -> Callable[ + [service.RawEncryptRequest], + Awaitable[service.RawEncryptResponse]]: + r"""Return a callable for the raw encrypt method over gRPC. + + Encrypts data using portable cryptographic primitives. Most + users should choose + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] and + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt] + rather than their raw counterparts. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.RawEncryptRequest], + Awaitable[~.RawEncryptResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'raw_encrypt' not in self._stubs: + self._stubs['raw_encrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/RawEncrypt', + request_serializer=service.RawEncryptRequest.serialize, + response_deserializer=service.RawEncryptResponse.deserialize, + ) + return self._stubs['raw_encrypt'] + + @property + def raw_decrypt(self) -> Callable[ + [service.RawDecryptRequest], + Awaitable[service.RawDecryptResponse]]: + r"""Return a callable for the raw decrypt method over gRPC. + + Decrypts data that was originally encrypted using a raw + cryptographic mechanism. The + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must + be + [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. + + Returns: + Callable[[~.RawDecryptRequest], + Awaitable[~.RawDecryptResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'raw_decrypt' not in self._stubs: + self._stubs['raw_decrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/RawDecrypt', + request_serializer=service.RawDecryptRequest.serialize, + response_deserializer=service.RawDecryptResponse.deserialize, + ) + return self._stubs['raw_decrypt'] + + @property + def asymmetric_sign(self) -> Callable[ + [service.AsymmetricSignRequest], + Awaitable[service.AsymmetricSignResponse]]: + r"""Return a callable for the asymmetric sign method over gRPC. + + Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_SIGN, producing a signature that can be verified with + the public key retrieved from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + Returns: + Callable[[~.AsymmetricSignRequest], + Awaitable[~.AsymmetricSignResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'asymmetric_sign' not in self._stubs: + self._stubs['asymmetric_sign'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/AsymmetricSign', + request_serializer=service.AsymmetricSignRequest.serialize, + response_deserializer=service.AsymmetricSignResponse.deserialize, + ) + return self._stubs['asymmetric_sign'] + + @property + def asymmetric_decrypt(self) -> Callable[ + [service.AsymmetricDecryptRequest], + Awaitable[service.AsymmetricDecryptResponse]]: + r"""Return a callable for the asymmetric decrypt method over gRPC. + + Decrypts data that was encrypted with a public key retrieved + from + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] + corresponding to a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + ASYMMETRIC_DECRYPT. + + Returns: + Callable[[~.AsymmetricDecryptRequest], + Awaitable[~.AsymmetricDecryptResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'asymmetric_decrypt' not in self._stubs: + self._stubs['asymmetric_decrypt'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/AsymmetricDecrypt', + request_serializer=service.AsymmetricDecryptRequest.serialize, + response_deserializer=service.AsymmetricDecryptResponse.deserialize, + ) + return self._stubs['asymmetric_decrypt'] + + @property + def mac_sign(self) -> Callable[ + [service.MacSignRequest], + Awaitable[service.MacSignResponse]]: + r"""Return a callable for the mac sign method over gRPC. + + Signs data using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + producing a tag that can be verified by another source with the + same key. + + Returns: + Callable[[~.MacSignRequest], + Awaitable[~.MacSignResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'mac_sign' not in self._stubs: + self._stubs['mac_sign'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/MacSign', + request_serializer=service.MacSignRequest.serialize, + response_deserializer=service.MacSignResponse.deserialize, + ) + return self._stubs['mac_sign'] + + @property + def mac_verify(self) -> Callable[ + [service.MacVerifyRequest], + Awaitable[service.MacVerifyResponse]]: + r"""Return a callable for the mac verify method over gRPC. + + Verifies MAC tag using a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, + and returns a response that indicates whether or not the + verification was successful. + + Returns: + Callable[[~.MacVerifyRequest], + Awaitable[~.MacVerifyResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'mac_verify' not in self._stubs: + self._stubs['mac_verify'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/MacVerify', + request_serializer=service.MacVerifyRequest.serialize, + response_deserializer=service.MacVerifyResponse.deserialize, + ) + return self._stubs['mac_verify'] + + @property + def generate_random_bytes(self) -> Callable[ + [service.GenerateRandomBytesRequest], + Awaitable[service.GenerateRandomBytesResponse]]: + r"""Return a callable for the generate random bytes method over gRPC. + + Generate random bytes using the Cloud KMS randomness + source in the provided location. + + Returns: + Callable[[~.GenerateRandomBytesRequest], + Awaitable[~.GenerateRandomBytesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if 'generate_random_bytes' not in self._stubs: + self._stubs['generate_random_bytes'] = self.grpc_channel.unary_unary( + '/google.cloud.kms.v1.KeyManagementService/GenerateRandomBytes', + request_serializer=service.GenerateRandomBytesRequest.serialize, + response_deserializer=service.GenerateRandomBytesResponse.deserialize, + ) + return self._stubs['generate_random_bytes'] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + Sets the IAM access control policy on the specified + function. Replaces any existing policy. + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/SetIamPolicy", + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + Gets the IAM access control policy for a function. + Returns an empty policy if the function exists and does + not have a policy set. + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/GetIamPolicy", + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + Tests the specified permissions against the IAM access control + policy for a function. If the function does not exist, this will + return an empty set of permissions, not a NOT_FOUND error. + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.iam.v1.IAMPolicy/TestIamPermissions", + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + def _prep_wrapped_messages(self, client_info): + """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_key_rings: self._wrap_method( + self.list_key_rings, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_crypto_keys: self._wrap_method( + self.list_crypto_keys, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_crypto_key_versions: self._wrap_method( + self.list_crypto_key_versions, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_import_jobs: self._wrap_method( + self.list_import_jobs, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_key_ring: self._wrap_method( + self.get_key_ring, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_crypto_key: self._wrap_method( + self.get_crypto_key, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_crypto_key_version: self._wrap_method( + self.get_crypto_key_version, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_public_key: self._wrap_method( + self.get_public_key, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_import_job: self._wrap_method( + self.get_import_job, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_key_ring: self._wrap_method( + self.create_key_ring, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_crypto_key: self._wrap_method( + self.create_crypto_key, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_crypto_key_version: self._wrap_method( + self.create_crypto_key_version, + default_timeout=60.0, + client_info=client_info, + ), + self.import_crypto_key_version: self._wrap_method( + self.import_crypto_key_version, + default_timeout=60.0, + client_info=client_info, + ), + self.create_import_job: self._wrap_method( + self.create_import_job, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_crypto_key: self._wrap_method( + self.update_crypto_key, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_crypto_key_version: self._wrap_method( + self.update_crypto_key_version, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_crypto_key_primary_version: self._wrap_method( + self.update_crypto_key_primary_version, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.destroy_crypto_key_version: self._wrap_method( + self.destroy_crypto_key_version, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.restore_crypto_key_version: self._wrap_method( + self.restore_crypto_key_version, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.encrypt: self._wrap_method( + self.encrypt, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.decrypt: self._wrap_method( + self.decrypt, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.raw_encrypt: self._wrap_method( + self.raw_encrypt, + default_timeout=None, + client_info=client_info, + ), + self.raw_decrypt: self._wrap_method( + self.raw_decrypt, + default_timeout=None, + client_info=client_info, + ), + self.asymmetric_sign: self._wrap_method( + self.asymmetric_sign, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.asymmetric_decrypt: self._wrap_method( + self.asymmetric_decrypt, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.mac_sign: self._wrap_method( + self.mac_sign, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.mac_verify: self._wrap_method( + self.mac_verify, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.generate_random_bytes: self._wrap_method( + self.generate_random_bytes, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_location: self._wrap_method( + self.get_location, + default_timeout=None, + client_info=client_info, + ), + self.list_locations: self._wrap_method( + self.list_locations, + default_timeout=None, + client_info=client_info, + ), + self.get_iam_policy: self._wrap_method( + self.get_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.set_iam_policy: self._wrap_method( + self.set_iam_policy, + default_timeout=None, + client_info=client_info, + ), + self.test_iam_permissions: self._wrap_method( + self.test_iam_permissions, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @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_locations( + self, + ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + + +__all__ = ( + 'KeyManagementServiceGrpcAsyncIOTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest.py new file mode 100644 index 000000000000..52f7bfa80310 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest.py @@ -0,0 +1,4008 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 +from google.auth import credentials as ga_credentials # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.api_core import rest_helpers +from google.api_core import rest_streaming +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore + +from requests import __version__ as requests_version +import dataclasses +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + + +from google.cloud.kms_v1.types import resources +from google.cloud.kms_v1.types import service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +from .rest_base import _BaseKeyManagementServiceRestTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + + +class KeyManagementServiceRestInterceptor: + """Interceptor for KeyManagementService. + + 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 KeyManagementServiceRestTransport. + + .. code-block:: python + class MyCustomKeyManagementServiceInterceptor(KeyManagementServiceRestInterceptor): + def pre_asymmetric_decrypt(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_asymmetric_decrypt(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_asymmetric_sign(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_asymmetric_sign(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_crypto_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_crypto_key(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_import_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_import_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_key_ring(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_key_ring(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_decrypt(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_decrypt(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_destroy_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_destroy_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_encrypt(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_encrypt(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_generate_random_bytes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_random_bytes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_crypto_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_crypto_key(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_import_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_import_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_key_ring(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_key_ring(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_public_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_public_key(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_import_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_crypto_keys(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_crypto_keys(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_crypto_key_versions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_crypto_key_versions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_import_jobs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_import_jobs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_key_rings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_key_rings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_mac_sign(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_mac_sign(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_mac_verify(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_mac_verify(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_raw_decrypt(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_raw_decrypt(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_raw_encrypt(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_raw_encrypt(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_restore_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_restore_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_crypto_key(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_crypto_key(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_crypto_key_primary_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_crypto_key_primary_version(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + + transport = KeyManagementServiceRestTransport(interceptor=MyCustomKeyManagementServiceInterceptor()) + client = KeyManagementServiceClient(transport=transport) + + + """ + def pre_asymmetric_decrypt(self, request: service.AsymmetricDecryptRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.AsymmetricDecryptRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for asymmetric_decrypt + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_asymmetric_decrypt(self, response: service.AsymmetricDecryptResponse) -> service.AsymmetricDecryptResponse: + """Post-rpc interceptor for asymmetric_decrypt + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_asymmetric_sign(self, request: service.AsymmetricSignRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.AsymmetricSignRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for asymmetric_sign + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_asymmetric_sign(self, response: service.AsymmetricSignResponse) -> service.AsymmetricSignResponse: + """Post-rpc interceptor for asymmetric_sign + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_create_crypto_key(self, request: service.CreateCryptoKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateCryptoKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_crypto_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_create_crypto_key(self, response: resources.CryptoKey) -> resources.CryptoKey: + """Post-rpc interceptor for create_crypto_key + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_create_crypto_key_version(self, request: service.CreateCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_create_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for create_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_create_import_job(self, request: service.CreateImportJobRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateImportJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_import_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_create_import_job(self, response: resources.ImportJob) -> resources.ImportJob: + """Post-rpc interceptor for create_import_job + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_create_key_ring(self, request: service.CreateKeyRingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateKeyRingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_key_ring + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_create_key_ring(self, response: resources.KeyRing) -> resources.KeyRing: + """Post-rpc interceptor for create_key_ring + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_decrypt(self, request: service.DecryptRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DecryptRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for decrypt + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_decrypt(self, response: service.DecryptResponse) -> service.DecryptResponse: + """Post-rpc interceptor for decrypt + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_destroy_crypto_key_version(self, request: service.DestroyCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DestroyCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for destroy_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_destroy_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for destroy_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_encrypt(self, request: service.EncryptRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.EncryptRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for encrypt + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_encrypt(self, response: service.EncryptResponse) -> service.EncryptResponse: + """Post-rpc interceptor for encrypt + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_generate_random_bytes(self, request: service.GenerateRandomBytesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GenerateRandomBytesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_random_bytes + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_generate_random_bytes(self, response: service.GenerateRandomBytesResponse) -> service.GenerateRandomBytesResponse: + """Post-rpc interceptor for generate_random_bytes + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_crypto_key(self, request: service.GetCryptoKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetCryptoKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_crypto_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_crypto_key(self, response: resources.CryptoKey) -> resources.CryptoKey: + """Post-rpc interceptor for get_crypto_key + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_crypto_key_version(self, request: service.GetCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for get_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_import_job(self, request: service.GetImportJobRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetImportJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_import_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_import_job(self, response: resources.ImportJob) -> resources.ImportJob: + """Post-rpc interceptor for get_import_job + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_key_ring(self, request: service.GetKeyRingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetKeyRingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_key_ring + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_key_ring(self, response: resources.KeyRing) -> resources.KeyRing: + """Post-rpc interceptor for get_key_ring + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_public_key(self, request: service.GetPublicKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetPublicKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_public_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_public_key(self, response: resources.PublicKey) -> resources.PublicKey: + """Post-rpc interceptor for get_public_key + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_import_crypto_key_version(self, request: service.ImportCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ImportCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for import_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_import_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for import_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_list_crypto_keys(self, request: service.ListCryptoKeysRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListCryptoKeysRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_crypto_keys + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_list_crypto_keys(self, response: service.ListCryptoKeysResponse) -> service.ListCryptoKeysResponse: + """Post-rpc interceptor for list_crypto_keys + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_list_crypto_key_versions(self, request: service.ListCryptoKeyVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListCryptoKeyVersionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_crypto_key_versions + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_list_crypto_key_versions(self, response: service.ListCryptoKeyVersionsResponse) -> service.ListCryptoKeyVersionsResponse: + """Post-rpc interceptor for list_crypto_key_versions + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_list_import_jobs(self, request: service.ListImportJobsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListImportJobsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_import_jobs + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_list_import_jobs(self, response: service.ListImportJobsResponse) -> service.ListImportJobsResponse: + """Post-rpc interceptor for list_import_jobs + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_list_key_rings(self, request: service.ListKeyRingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListKeyRingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_key_rings + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_list_key_rings(self, response: service.ListKeyRingsResponse) -> service.ListKeyRingsResponse: + """Post-rpc interceptor for list_key_rings + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_mac_sign(self, request: service.MacSignRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.MacSignRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for mac_sign + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_mac_sign(self, response: service.MacSignResponse) -> service.MacSignResponse: + """Post-rpc interceptor for mac_sign + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_mac_verify(self, request: service.MacVerifyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.MacVerifyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for mac_verify + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_mac_verify(self, response: service.MacVerifyResponse) -> service.MacVerifyResponse: + """Post-rpc interceptor for mac_verify + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_raw_decrypt(self, request: service.RawDecryptRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RawDecryptRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for raw_decrypt + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_raw_decrypt(self, response: service.RawDecryptResponse) -> service.RawDecryptResponse: + """Post-rpc interceptor for raw_decrypt + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_raw_encrypt(self, request: service.RawEncryptRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RawEncryptRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for raw_encrypt + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_raw_encrypt(self, response: service.RawEncryptResponse) -> service.RawEncryptResponse: + """Post-rpc interceptor for raw_encrypt + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_restore_crypto_key_version(self, request: service.RestoreCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RestoreCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for restore_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_restore_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for restore_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_update_crypto_key(self, request: service.UpdateCryptoKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateCryptoKeyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_crypto_key + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_update_crypto_key(self, response: resources.CryptoKey) -> resources.CryptoKey: + """Post-rpc interceptor for update_crypto_key + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_update_crypto_key_primary_version(self, request: service.UpdateCryptoKeyPrimaryVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateCryptoKeyPrimaryVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_crypto_key_primary_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_update_crypto_key_primary_version(self, response: resources.CryptoKey) -> resources.CryptoKey: + """Post-rpc interceptor for update_crypto_key_primary_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_update_crypto_key_version(self, request: service.UpdateCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_update_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for update_crypto_key_version + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_location( + self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_get_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_set_iam_policy( + self, response: policy_pb2.Policy + ) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the KeyManagementService 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 KeyManagementService 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 KeyManagementService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class KeyManagementServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: KeyManagementServiceRestInterceptor + + +class KeyManagementServiceRestTransport(_BaseKeyManagementServiceRestTransport): + """REST backend synchronous transport for KeyManagementService. + + Google Cloud Key Management Service + + Manages cryptographic keys and operations using those keys. + Implements a REST model with the following objects: + + - [KeyRing][google.cloud.kms.v1.KeyRing] + - [CryptoKey][google.cloud.kms.v1.CryptoKey] + - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + - [ImportJob][google.cloud.kms.v1.ImportJob] + + If you are using manual gRPC libraries, see `Using gRPC with Cloud + KMS `__. + + 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 = 'cloudkms.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[KeyManagementServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or KeyManagementServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _AsymmetricDecrypt(_BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.AsymmetricDecrypt") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.AsymmetricDecryptRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.AsymmetricDecryptResponse: + r"""Call the asymmetric decrypt method over HTTP. + + Args: + request (~.service.AsymmetricDecryptRequest): + The request object. Request message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.AsymmetricDecryptResponse: + Response message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt._get_http_options() + request, metadata = self._interceptor.pre_asymmetric_decrypt(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._AsymmetricDecrypt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.AsymmetricDecryptResponse() + pb_resp = service.AsymmetricDecryptResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_asymmetric_decrypt(resp) + return resp + + class _AsymmetricSign(_BaseKeyManagementServiceRestTransport._BaseAsymmetricSign, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.AsymmetricSign") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.AsymmetricSignRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.AsymmetricSignResponse: + r"""Call the asymmetric sign method over HTTP. + + Args: + request (~.service.AsymmetricSignRequest): + The request object. Request message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.AsymmetricSignResponse: + Response message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseAsymmetricSign._get_http_options() + request, metadata = self._interceptor.pre_asymmetric_sign(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseAsymmetricSign._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseAsymmetricSign._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseAsymmetricSign._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._AsymmetricSign._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.AsymmetricSignResponse() + pb_resp = service.AsymmetricSignResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_asymmetric_sign(resp) + return resp + + class _CreateCryptoKey(_BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.CreateCryptoKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.CreateCryptoKeyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CryptoKey: + r"""Call the create crypto key method over HTTP. + + Args: + request (~.service.CreateCryptoKeyRequest): + The request object. Request message for + [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents + a logical key that can be used for cryptographic + operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up + of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], which + represent the actual key material used in cryptographic + operations. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey._get_http_options() + request, metadata = self._interceptor.pre_create_crypto_key(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._CreateCryptoKey._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CryptoKey() + pb_resp = resources.CryptoKey.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_crypto_key(resp) + return resp + + class _CreateCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.CreateCryptoKeyVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.CreateCryptoKeyVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CryptoKeyVersion: + r"""Call the create crypto key version method over HTTP. + + Args: + request (~.service.CreateCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion._get_http_options() + request, metadata = self._interceptor.pre_create_crypto_key_version(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._CreateCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_crypto_key_version(resp) + return resp + + class _CreateImportJob(_BaseKeyManagementServiceRestTransport._BaseCreateImportJob, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.CreateImportJob") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.CreateImportJobRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.ImportJob: + r"""Call the create import job method over HTTP. + + Args: + request (~.service.CreateImportJobRequest): + The request object. Request message for + [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be + used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", which + is a public/private key pair. You use the wrapping key + to encrypt (also known as wrap) the pre-existing key + material to protect it during the import process. The + nature of the wrapping key depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be set + to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be used + to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 + days after it is created. Once expired, Cloud KMS will + no longer be able to import or unwrap any key material + that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. + + For more information, see `Importing a + key `__. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseCreateImportJob._get_http_options() + request, metadata = self._interceptor.pre_create_import_job(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseCreateImportJob._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseCreateImportJob._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseCreateImportJob._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._CreateImportJob._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.ImportJob() + pb_resp = resources.ImportJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_import_job(resp) + return resp + + class _CreateKeyRing(_BaseKeyManagementServiceRestTransport._BaseCreateKeyRing, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.CreateKeyRing") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.CreateKeyRingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.KeyRing: + r"""Call the create key ring method over HTTP. + + Args: + request (~.service.CreateKeyRingRequest): + The request object. Request message for + [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.KeyRing: + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel + logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseCreateKeyRing._get_http_options() + request, metadata = self._interceptor.pre_create_key_ring(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseCreateKeyRing._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseCreateKeyRing._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseCreateKeyRing._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._CreateKeyRing._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.KeyRing() + pb_resp = resources.KeyRing.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_key_ring(resp) + return resp + + class _Decrypt(_BaseKeyManagementServiceRestTransport._BaseDecrypt, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.Decrypt") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.DecryptRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.DecryptResponse: + r"""Call the decrypt method over HTTP. + + Args: + request (~.service.DecryptRequest): + The request object. Request message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.DecryptResponse: + Response message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseDecrypt._get_http_options() + request, metadata = self._interceptor.pre_decrypt(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseDecrypt._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseDecrypt._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseDecrypt._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._Decrypt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.DecryptResponse() + pb_resp = service.DecryptResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_decrypt(resp) + return resp + + class _DestroyCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.DestroyCryptoKeyVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.DestroyCryptoKeyVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CryptoKeyVersion: + r"""Call the destroy crypto key + version method over HTTP. + + Args: + request (~.service.DestroyCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion._get_http_options() + request, metadata = self._interceptor.pre_destroy_crypto_key_version(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._DestroyCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_destroy_crypto_key_version(resp) + return resp + + class _Encrypt(_BaseKeyManagementServiceRestTransport._BaseEncrypt, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.Encrypt") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.EncryptRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.EncryptResponse: + r"""Call the encrypt method over HTTP. + + Args: + request (~.service.EncryptRequest): + The request object. Request message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.EncryptResponse: + Response message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseEncrypt._get_http_options() + request, metadata = self._interceptor.pre_encrypt(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseEncrypt._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseEncrypt._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseEncrypt._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._Encrypt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.EncryptResponse() + pb_resp = service.EncryptResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_encrypt(resp) + return resp + + class _GenerateRandomBytes(_BaseKeyManagementServiceRestTransport._BaseGenerateRandomBytes, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.GenerateRandomBytes") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.GenerateRandomBytesRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.GenerateRandomBytesResponse: + r"""Call the generate random bytes method over HTTP. + + Args: + request (~.service.GenerateRandomBytesRequest): + The request object. Request message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.GenerateRandomBytesResponse: + Response message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseGenerateRandomBytes._get_http_options() + request, metadata = self._interceptor.pre_generate_random_bytes(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGenerateRandomBytes._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseGenerateRandomBytes._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseGenerateRandomBytes._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._GenerateRandomBytes._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.GenerateRandomBytesResponse() + pb_resp = service.GenerateRandomBytesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_random_bytes(resp) + return resp + + class _GetCryptoKey(_BaseKeyManagementServiceRestTransport._BaseGetCryptoKey, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.GetCryptoKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: service.GetCryptoKeyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CryptoKey: + r"""Call the get crypto key method over HTTP. + + Args: + request (~.service.GetCryptoKeyRequest): + The request object. Request message for + [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents + a logical key that can be used for cryptographic + operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up + of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], which + represent the actual key material used in cryptographic + operations. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKey._get_http_options() + request, metadata = self._interceptor.pre_get_crypto_key(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKey._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKey._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._GetCryptoKey._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CryptoKey() + pb_resp = resources.CryptoKey.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_crypto_key(resp) + return resp + + class _GetCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseGetCryptoKeyVersion, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.GetCryptoKeyVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: service.GetCryptoKeyVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CryptoKeyVersion: + r"""Call the get crypto key version method over HTTP. + + Args: + request (~.service.GetCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKeyVersion._get_http_options() + request, metadata = self._interceptor.pre_get_crypto_key_version(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKeyVersion._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKeyVersion._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._GetCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_crypto_key_version(resp) + return resp + + class _GetImportJob(_BaseKeyManagementServiceRestTransport._BaseGetImportJob, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.GetImportJob") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: service.GetImportJobRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.ImportJob: + r"""Call the get import job method over HTTP. + + Args: + request (~.service.GetImportJobRequest): + The request object. Request message for + [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ImportJob: + An [ImportJob][google.cloud.kms.v1.ImportJob] can be + used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + using pre-existing key material, generated outside of + Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is + created, Cloud KMS will generate a "wrapping key", which + is a public/private key pair. You use the wrapping key + to encrypt (also known as wrap) the pre-existing key + material to protect it during the import process. The + nature of the wrapping key depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. + When the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be set + to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + and the + [public_key][google.cloud.kms.v1.ImportJob.public_key] + can be fetched. The fetched public key can then be used + to wrap your pre-existing key material. + + Once the key material is wrapped, it can be imported + into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + in an existing + [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS + uses the private key portion of the wrapping key to + unwrap the key material. Only Cloud KMS has access to + the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 + days after it is created. Once expired, Cloud KMS will + no longer be able to import or unwrap any key material + that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. + + For more information, see `Importing a + key `__. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseGetImportJob._get_http_options() + request, metadata = self._interceptor.pre_get_import_job(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetImportJob._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseGetImportJob._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._GetImportJob._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.ImportJob() + pb_resp = resources.ImportJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_import_job(resp) + return resp + + class _GetKeyRing(_BaseKeyManagementServiceRestTransport._BaseGetKeyRing, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.GetKeyRing") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: service.GetKeyRingRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.KeyRing: + r"""Call the get key ring method over HTTP. + + Args: + request (~.service.GetKeyRingRequest): + The request object. Request message for + [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.KeyRing: + A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel + logical grouping of + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseGetKeyRing._get_http_options() + request, metadata = self._interceptor.pre_get_key_ring(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetKeyRing._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseGetKeyRing._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._GetKeyRing._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.KeyRing() + pb_resp = resources.KeyRing.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_key_ring(resp) + return resp + + class _GetPublicKey(_BaseKeyManagementServiceRestTransport._BaseGetPublicKey, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.GetPublicKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: service.GetPublicKeyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.PublicKey: + r"""Call the get public key method over HTTP. + + Args: + request (~.service.GetPublicKeyRequest): + The request object. Request message for + [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.PublicKey: + The public keys for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + Obtained via + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseGetPublicKey._get_http_options() + request, metadata = self._interceptor.pre_get_public_key(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetPublicKey._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseGetPublicKey._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._GetPublicKey._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.PublicKey() + pb_resp = resources.PublicKey.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_public_key(resp) + return resp + + class _ImportCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.ImportCryptoKeyVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.ImportCryptoKeyVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CryptoKeyVersion: + r"""Call the import crypto key version method over HTTP. + + Args: + request (~.service.ImportCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion._get_http_options() + request, metadata = self._interceptor.pre_import_crypto_key_version(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._ImportCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_import_crypto_key_version(resp) + return resp + + class _ListCryptoKeys(_BaseKeyManagementServiceRestTransport._BaseListCryptoKeys, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.ListCryptoKeys") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: service.ListCryptoKeysRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListCryptoKeysResponse: + r"""Call the list crypto keys method over HTTP. + + Args: + request (~.service.ListCryptoKeysRequest): + The request object. Request message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCryptoKeysResponse: + Response message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeys._get_http_options() + request, metadata = self._interceptor.pre_list_crypto_keys(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeys._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeys._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._ListCryptoKeys._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCryptoKeysResponse() + pb_resp = service.ListCryptoKeysResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_crypto_keys(resp) + return resp + + class _ListCryptoKeyVersions(_BaseKeyManagementServiceRestTransport._BaseListCryptoKeyVersions, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.ListCryptoKeyVersions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: service.ListCryptoKeyVersionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListCryptoKeyVersionsResponse: + r"""Call the list crypto key versions method over HTTP. + + Args: + request (~.service.ListCryptoKeyVersionsRequest): + The request object. Request message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListCryptoKeyVersionsResponse: + Response message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeyVersions._get_http_options() + request, metadata = self._interceptor.pre_list_crypto_key_versions(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeyVersions._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeyVersions._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._ListCryptoKeyVersions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListCryptoKeyVersionsResponse() + pb_resp = service.ListCryptoKeyVersionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_crypto_key_versions(resp) + return resp + + class _ListImportJobs(_BaseKeyManagementServiceRestTransport._BaseListImportJobs, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.ListImportJobs") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: service.ListImportJobsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListImportJobsResponse: + r"""Call the list import jobs method over HTTP. + + Args: + request (~.service.ListImportJobsRequest): + The request object. Request message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListImportJobsResponse: + Response message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseListImportJobs._get_http_options() + request, metadata = self._interceptor.pre_list_import_jobs(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseListImportJobs._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseListImportJobs._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._ListImportJobs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListImportJobsResponse() + pb_resp = service.ListImportJobsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_import_jobs(resp) + return resp + + class _ListKeyRings(_BaseKeyManagementServiceRestTransport._BaseListKeyRings, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.ListKeyRings") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: service.ListKeyRingsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.ListKeyRingsResponse: + r"""Call the list key rings method over HTTP. + + Args: + request (~.service.ListKeyRingsRequest): + The request object. Request message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.ListKeyRingsResponse: + Response message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseListKeyRings._get_http_options() + request, metadata = self._interceptor.pre_list_key_rings(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseListKeyRings._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseListKeyRings._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._ListKeyRings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.ListKeyRingsResponse() + pb_resp = service.ListKeyRingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_key_rings(resp) + return resp + + class _MacSign(_BaseKeyManagementServiceRestTransport._BaseMacSign, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.MacSign") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.MacSignRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.MacSignResponse: + r"""Call the mac sign method over HTTP. + + Args: + request (~.service.MacSignRequest): + The request object. Request message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.MacSignResponse: + Response message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseMacSign._get_http_options() + request, metadata = self._interceptor.pre_mac_sign(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseMacSign._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseMacSign._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseMacSign._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._MacSign._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.MacSignResponse() + pb_resp = service.MacSignResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_mac_sign(resp) + return resp + + class _MacVerify(_BaseKeyManagementServiceRestTransport._BaseMacVerify, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.MacVerify") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.MacVerifyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.MacVerifyResponse: + r"""Call the mac verify method over HTTP. + + Args: + request (~.service.MacVerifyRequest): + The request object. Request message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.MacVerifyResponse: + Response message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseMacVerify._get_http_options() + request, metadata = self._interceptor.pre_mac_verify(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseMacVerify._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseMacVerify._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseMacVerify._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._MacVerify._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.MacVerifyResponse() + pb_resp = service.MacVerifyResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_mac_verify(resp) + return resp + + class _RawDecrypt(_BaseKeyManagementServiceRestTransport._BaseRawDecrypt, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.RawDecrypt") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.RawDecryptRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.RawDecryptResponse: + r"""Call the raw decrypt method over HTTP. + + Args: + request (~.service.RawDecryptRequest): + The request object. Request message for + [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.RawDecryptResponse: + Response message for + [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseRawDecrypt._get_http_options() + request, metadata = self._interceptor.pre_raw_decrypt(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseRawDecrypt._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseRawDecrypt._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseRawDecrypt._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._RawDecrypt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.RawDecryptResponse() + pb_resp = service.RawDecryptResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_raw_decrypt(resp) + return resp + + class _RawEncrypt(_BaseKeyManagementServiceRestTransport._BaseRawEncrypt, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.RawEncrypt") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.RawEncryptRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> service.RawEncryptResponse: + r"""Call the raw encrypt method over HTTP. + + Args: + request (~.service.RawEncryptRequest): + The request object. Request message for + [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.RawEncryptResponse: + Response message for + [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseRawEncrypt._get_http_options() + request, metadata = self._interceptor.pre_raw_encrypt(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseRawEncrypt._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseRawEncrypt._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseRawEncrypt._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._RawEncrypt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.RawEncryptResponse() + pb_resp = service.RawEncryptResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_raw_encrypt(resp) + return resp + + class _RestoreCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.RestoreCryptoKeyVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.RestoreCryptoKeyVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CryptoKeyVersion: + r"""Call the restore crypto key + version method over HTTP. + + Args: + request (~.service.RestoreCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion._get_http_options() + request, metadata = self._interceptor.pre_restore_crypto_key_version(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._RestoreCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_restore_crypto_key_version(resp) + return resp + + class _UpdateCryptoKey(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.UpdateCryptoKey") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.UpdateCryptoKeyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CryptoKey: + r"""Call the update crypto key method over HTTP. + + Args: + request (~.service.UpdateCryptoKeyRequest): + The request object. Request message for + [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents + a logical key that can be used for cryptographic + operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up + of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], which + represent the actual key material used in cryptographic + operations. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey._get_http_options() + request, metadata = self._interceptor.pre_update_crypto_key(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._UpdateCryptoKey._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CryptoKey() + pb_resp = resources.CryptoKey.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_crypto_key(resp) + return resp + + class _UpdateCryptoKeyPrimaryVersion(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.UpdateCryptoKeyPrimaryVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.UpdateCryptoKeyPrimaryVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CryptoKey: + r"""Call the update crypto key primary + version method over HTTP. + + Args: + request (~.service.UpdateCryptoKeyPrimaryVersionRequest): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CryptoKey: + A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents + a logical key that can be used for cryptographic + operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up + of zero or more + [versions][google.cloud.kms.v1.CryptoKeyVersion], which + represent the actual key material used in cryptographic + operations. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion._get_http_options() + request, metadata = self._interceptor.pre_update_crypto_key_primary_version(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._UpdateCryptoKeyPrimaryVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CryptoKey() + pb_resp = resources.CryptoKey.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_crypto_key_primary_version(resp) + return resp + + class _UpdateCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.UpdateCryptoKeyVersion") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: service.UpdateCryptoKeyVersionRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> resources.CryptoKeyVersion: + r"""Call the update crypto key version method over HTTP. + + Args: + request (~.service.UpdateCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion._get_http_options() + request, metadata = self._interceptor.pre_update_crypto_key_version(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._UpdateCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_crypto_key_version(resp) + return resp + + @property + def asymmetric_decrypt(self) -> Callable[ + [service.AsymmetricDecryptRequest], + service.AsymmetricDecryptResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AsymmetricDecrypt(self._session, self._host, self._interceptor) # type: ignore + + @property + def asymmetric_sign(self) -> Callable[ + [service.AsymmetricSignRequest], + service.AsymmetricSignResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AsymmetricSign(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_crypto_key(self) -> Callable[ + [service.CreateCryptoKeyRequest], + resources.CryptoKey]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCryptoKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_crypto_key_version(self) -> Callable[ + [service.CreateCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_import_job(self) -> Callable[ + [service.CreateImportJobRequest], + resources.ImportJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateImportJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_key_ring(self) -> Callable[ + [service.CreateKeyRingRequest], + resources.KeyRing]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateKeyRing(self._session, self._host, self._interceptor) # type: ignore + + @property + def decrypt(self) -> Callable[ + [service.DecryptRequest], + service.DecryptResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Decrypt(self._session, self._host, self._interceptor) # type: ignore + + @property + def destroy_crypto_key_version(self) -> Callable[ + [service.DestroyCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DestroyCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def encrypt(self) -> Callable[ + [service.EncryptRequest], + service.EncryptResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Encrypt(self._session, self._host, self._interceptor) # type: ignore + + @property + def generate_random_bytes(self) -> Callable[ + [service.GenerateRandomBytesRequest], + service.GenerateRandomBytesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateRandomBytes(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_crypto_key(self) -> Callable[ + [service.GetCryptoKeyRequest], + resources.CryptoKey]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCryptoKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_crypto_key_version(self) -> Callable[ + [service.GetCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_import_job(self) -> Callable[ + [service.GetImportJobRequest], + resources.ImportJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetImportJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_key_ring(self) -> Callable[ + [service.GetKeyRingRequest], + resources.KeyRing]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetKeyRing(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_public_key(self) -> Callable[ + [service.GetPublicKeyRequest], + resources.PublicKey]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetPublicKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def import_crypto_key_version(self) -> Callable[ + [service.ImportCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ImportCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_crypto_keys(self) -> Callable[ + [service.ListCryptoKeysRequest], + service.ListCryptoKeysResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCryptoKeys(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_crypto_key_versions(self) -> Callable[ + [service.ListCryptoKeyVersionsRequest], + service.ListCryptoKeyVersionsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListCryptoKeyVersions(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_import_jobs(self) -> Callable[ + [service.ListImportJobsRequest], + service.ListImportJobsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListImportJobs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_key_rings(self) -> Callable[ + [service.ListKeyRingsRequest], + service.ListKeyRingsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListKeyRings(self._session, self._host, self._interceptor) # type: ignore + + @property + def mac_sign(self) -> Callable[ + [service.MacSignRequest], + service.MacSignResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._MacSign(self._session, self._host, self._interceptor) # type: ignore + + @property + def mac_verify(self) -> Callable[ + [service.MacVerifyRequest], + service.MacVerifyResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._MacVerify(self._session, self._host, self._interceptor) # type: ignore + + @property + def raw_decrypt(self) -> Callable[ + [service.RawDecryptRequest], + service.RawDecryptResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RawDecrypt(self._session, self._host, self._interceptor) # type: ignore + + @property + def raw_encrypt(self) -> Callable[ + [service.RawEncryptRequest], + service.RawEncryptResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RawEncrypt(self._session, self._host, self._interceptor) # type: ignore + + @property + def restore_crypto_key_version(self) -> Callable[ + [service.RestoreCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RestoreCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_crypto_key(self) -> Callable[ + [service.UpdateCryptoKeyRequest], + resources.CryptoKey]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCryptoKey(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_crypto_key_primary_version(self) -> Callable[ + [service.UpdateCryptoKeyPrimaryVersionRequest], + resources.CryptoKey]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCryptoKeyPrimaryVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_crypto_key_version(self) -> Callable[ + [service.UpdateCryptoKeyVersionRequest], + resources.CryptoKeyVersion]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_location(self): + return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore + + class _GetLocation(_BaseKeyManagementServiceRestTransport._BaseGetLocation, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.GetLocation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.GetLocationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.Location: + + r"""Call the get location method over HTTP. + + Args: + request (locations_pb2.GetLocationRequest): + The request object for GetLocation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.Location: Response from GetLocation method. + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseGetLocation._get_http_options() + request, metadata = self._interceptor.pre_get_location(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.Location() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_location(resp) + return resp + + @property + def list_locations(self): + return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore + + class _ListLocations(_BaseKeyManagementServiceRestTransport._BaseListLocations, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.ListLocations") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: locations_pb2.ListLocationsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> locations_pb2.ListLocationsResponse: + + r"""Call the list locations method over HTTP. + + Args: + request (locations_pb2.ListLocationsRequest): + The request object for ListLocations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + locations_pb2.ListLocationsResponse: Response from ListLocations method. + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseListLocations._get_http_options() + request, metadata = self._interceptor.pre_list_locations(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = locations_pb2.ListLocationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_locations(resp) + return resp + + @property + def get_iam_policy(self): + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _GetIamPolicy(_BaseKeyManagementServiceRestTransport._BaseGetIamPolicy, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.GetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: iam_policy_pb2.GetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the get iam policy method over HTTP. + + Args: + request (iam_policy_pb2.GetIamPolicyRequest): + The request object for GetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from GetIamPolicy method. + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseGetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + @property + def set_iam_policy(self): + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + class _SetIamPolicy(_BaseKeyManagementServiceRestTransport._BaseSetIamPolicy, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.SetIamPolicy") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.SetIamPolicyRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> policy_pb2.Policy: + + r"""Call the set iam policy method over HTTP. + + Args: + request (iam_policy_pb2.SetIamPolicyRequest): + The request object for SetIamPolicy method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + policy_pb2.Policy: Response from SetIamPolicy method. + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseSetIamPolicy._get_http_options() + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = policy_pb2.Policy() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + @property + def test_iam_permissions(self): + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + class _TestIamPermissions(_BaseKeyManagementServiceRestTransport._BaseTestIamPermissions, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.TestIamPermissions") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__(self, + request: iam_policy_pb2.TestIamPermissionsRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, str]]=(), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + + r"""Call the test iam permissions method over HTTP. + + Args: + request (iam_policy_pb2.TestIamPermissionsRequest): + The request object for TestIamPermissions method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseTestIamPermissions._get_http_options() + request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) + + body = _BaseKeyManagementServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = iam_policy_pb2.TestIamPermissionsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(_BaseKeyManagementServiceRestTransport._BaseGetOperation, KeyManagementServiceRestStub): + def __hash__(self): + return hash("KeyManagementServiceRestTransport.GetOperation") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None): + + uri = transcoded_request['uri'] + method = transcoded_request['method'] + headers = dict(metadata) + headers['Content-Type'] = 'application/json' + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__(self, + request: operations_pb2.GetOperationRequest, *, + retry: OptionalRetry=gapic_v1.method.DEFAULT, + timeout: Optional[float]=None, + metadata: Sequence[Tuple[str, 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 = _BaseKeyManagementServiceRestTransport._BaseGetOperation._get_http_options() + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) + + # Send the request + response = KeyManagementServiceRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__=( + 'KeyManagementServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py new file mode 100644 index 000000000000..895c4a385558 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py @@ -0,0 +1,1532 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import json # type: ignore +from google.api_core import path_template +from google.api_core import gapic_v1 + +from google.protobuf import json_format +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from .base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO + +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + + +from google.cloud.kms_v1.types import resources +from google.cloud.kms_v1.types import service +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + + +class _BaseKeyManagementServiceRestTransport(KeyManagementServiceTransport): + """Base REST backend transport for KeyManagementService. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__(self, *, + host: str = 'cloudkms.googleapis.com', + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = 'https', + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'cloudkms.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience + ) + + class _BaseAsymmetricDecrypt: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricDecrypt', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.AsymmetricDecryptRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseAsymmetricSign: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricSign', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.AsymmetricSignRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseAsymmetricSign._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCryptoKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "cryptoKeyId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys', + 'body': 'crypto_key', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateCryptoKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateCryptoKeyVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions', + 'body': 'crypto_key_version', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateCryptoKeyVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateImportJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "importJobId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*}/importJobs', + 'body': 'import_job', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateImportJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseCreateImportJob._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseCreateKeyRing: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "keyRingId" : "", } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*}/keyRings', + 'body': 'key_ring', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.CreateKeyRingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseCreateKeyRing._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDecrypt: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}:decrypt', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DecryptRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseDecrypt._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseDestroyCryptoKeyVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:destroy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.DestroyCryptoKeyVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseEncrypt: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/**}:encrypt', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.EncryptRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseEncrypt._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGenerateRandomBytes: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{location=projects/*/locations/*}:generateRandomBytes', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GenerateRandomBytesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCryptoKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetCryptoKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseGetCryptoKey._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCryptoKeyVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetCryptoKeyVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseGetCryptoKeyVersion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetImportJob: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/importJobs/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetImportJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseGetImportJob._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetKeyRing: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetKeyRingRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseGetKeyRing._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetPublicKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}/publicKey', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.GetPublicKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseGetPublicKey._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseImportCryptoKeyVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions:import', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ImportCryptoKeyVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCryptoKeys: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListCryptoKeysRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseListCryptoKeys._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListCryptoKeyVersions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListCryptoKeyVersionsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseListCryptoKeyVersions._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListImportJobs: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*}/importJobs', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListImportJobsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseListImportJobs._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListKeyRings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{parent=projects/*/locations/*}/keyRings', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListKeyRingsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseListKeyRings._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMacSign: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macSign', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.MacSignRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseMacSign._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseMacVerify: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macVerify', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.MacVerifyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseMacVerify._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRawDecrypt: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:rawDecrypt', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.RawDecryptRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseRawDecrypt._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRawEncrypt: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:rawEncrypt', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.RawEncryptRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseRawEncrypt._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRestoreCryptoKeyVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:restore', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.RestoreCryptoKeyVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCryptoKey: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{crypto_key.name=projects/*/locations/*/keyRings/*/cryptoKeys/*}', + 'body': 'crypto_key', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateCryptoKeyRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCryptoKeyPrimaryVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}:updatePrimaryVersion', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateCryptoKeyPrimaryVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseUpdateCryptoKeyVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "updateMask" : {}, } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'patch', + 'uri': '/v1/{crypto_key_version.name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}', + 'body': 'crypto_key_version', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.UpdateCryptoKeyVersionRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request['body'], + use_integers_for_enums=True + ) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json_format.MessageToJson( + transcoded_request['query_params'], + use_integers_for_enums=True, + )) + query_params.update(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetLocation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseListLocations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*}/locations', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:getIamPolicy', + }, + { + 'method': 'get', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:getIamPolicy', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseSetIamPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:setIamPolicy', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:setIamPolicy', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseTestIamPermissions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:testIamPermissions', + 'body': '*', + }, + { + 'method': 'post', + 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:testIamPermissions', + 'body': '*', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + body = json.dumps(transcoded_request['body']) + return body + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [{ + 'method': 'get', + 'uri': '/v1/{name=projects/*/locations/*/operations/*}', + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode( + http_options, **request_kwargs) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads(json.dumps(transcoded_request['query_params'])) + return query_params + + +__all__=( + '_BaseKeyManagementServiceRestTransport', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/__init__.py new file mode 100644 index 000000000000..c5fb762a3035 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/__init__.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .autokey import ( + CreateKeyHandleMetadata, + CreateKeyHandleRequest, + GetKeyHandleRequest, + KeyHandle, + ListKeyHandlesRequest, + ListKeyHandlesResponse, +) +from .autokey_admin import ( + AutokeyConfig, + GetAutokeyConfigRequest, + ShowEffectiveAutokeyConfigRequest, + ShowEffectiveAutokeyConfigResponse, + UpdateAutokeyConfigRequest, +) +from .ekm_service import ( + Certificate, + CreateEkmConnectionRequest, + EkmConfig, + EkmConnection, + GetEkmConfigRequest, + GetEkmConnectionRequest, + ListEkmConnectionsRequest, + ListEkmConnectionsResponse, + UpdateEkmConfigRequest, + UpdateEkmConnectionRequest, + VerifyConnectivityRequest, + VerifyConnectivityResponse, +) +from .resources import ( + CryptoKey, + CryptoKeyVersion, + CryptoKeyVersionTemplate, + ExternalProtectionLevelOptions, + ImportJob, + KeyAccessJustificationsPolicy, + KeyOperationAttestation, + KeyRing, + PublicKey, + AccessReason, + ProtectionLevel, +) +from .service import ( + AsymmetricDecryptRequest, + AsymmetricDecryptResponse, + AsymmetricSignRequest, + AsymmetricSignResponse, + CreateCryptoKeyRequest, + CreateCryptoKeyVersionRequest, + CreateImportJobRequest, + CreateKeyRingRequest, + DecryptRequest, + DecryptResponse, + DestroyCryptoKeyVersionRequest, + Digest, + EncryptRequest, + EncryptResponse, + GenerateRandomBytesRequest, + GenerateRandomBytesResponse, + GetCryptoKeyRequest, + GetCryptoKeyVersionRequest, + GetImportJobRequest, + GetKeyRingRequest, + GetPublicKeyRequest, + ImportCryptoKeyVersionRequest, + ListCryptoKeysRequest, + ListCryptoKeysResponse, + ListCryptoKeyVersionsRequest, + ListCryptoKeyVersionsResponse, + ListImportJobsRequest, + ListImportJobsResponse, + ListKeyRingsRequest, + ListKeyRingsResponse, + LocationMetadata, + MacSignRequest, + MacSignResponse, + MacVerifyRequest, + MacVerifyResponse, + RawDecryptRequest, + RawDecryptResponse, + RawEncryptRequest, + RawEncryptResponse, + RestoreCryptoKeyVersionRequest, + UpdateCryptoKeyPrimaryVersionRequest, + UpdateCryptoKeyRequest, + UpdateCryptoKeyVersionRequest, +) + +__all__ = ( + 'CreateKeyHandleMetadata', + 'CreateKeyHandleRequest', + 'GetKeyHandleRequest', + 'KeyHandle', + 'ListKeyHandlesRequest', + 'ListKeyHandlesResponse', + 'AutokeyConfig', + 'GetAutokeyConfigRequest', + 'ShowEffectiveAutokeyConfigRequest', + 'ShowEffectiveAutokeyConfigResponse', + 'UpdateAutokeyConfigRequest', + 'Certificate', + 'CreateEkmConnectionRequest', + 'EkmConfig', + 'EkmConnection', + 'GetEkmConfigRequest', + 'GetEkmConnectionRequest', + 'ListEkmConnectionsRequest', + 'ListEkmConnectionsResponse', + 'UpdateEkmConfigRequest', + 'UpdateEkmConnectionRequest', + 'VerifyConnectivityRequest', + 'VerifyConnectivityResponse', + 'CryptoKey', + 'CryptoKeyVersion', + 'CryptoKeyVersionTemplate', + 'ExternalProtectionLevelOptions', + 'ImportJob', + 'KeyAccessJustificationsPolicy', + 'KeyOperationAttestation', + 'KeyRing', + 'PublicKey', + 'AccessReason', + 'ProtectionLevel', + 'AsymmetricDecryptRequest', + 'AsymmetricDecryptResponse', + 'AsymmetricSignRequest', + 'AsymmetricSignResponse', + 'CreateCryptoKeyRequest', + 'CreateCryptoKeyVersionRequest', + 'CreateImportJobRequest', + 'CreateKeyRingRequest', + 'DecryptRequest', + 'DecryptResponse', + 'DestroyCryptoKeyVersionRequest', + 'Digest', + 'EncryptRequest', + 'EncryptResponse', + 'GenerateRandomBytesRequest', + 'GenerateRandomBytesResponse', + 'GetCryptoKeyRequest', + 'GetCryptoKeyVersionRequest', + 'GetImportJobRequest', + 'GetKeyRingRequest', + 'GetPublicKeyRequest', + 'ImportCryptoKeyVersionRequest', + 'ListCryptoKeysRequest', + 'ListCryptoKeysResponse', + 'ListCryptoKeyVersionsRequest', + 'ListCryptoKeyVersionsResponse', + 'ListImportJobsRequest', + 'ListImportJobsResponse', + 'ListKeyRingsRequest', + 'ListKeyRingsResponse', + 'LocationMetadata', + 'MacSignRequest', + 'MacSignResponse', + 'MacVerifyRequest', + 'MacVerifyResponse', + 'RawDecryptRequest', + 'RawDecryptResponse', + 'RawEncryptRequest', + 'RawEncryptResponse', + 'RestoreCryptoKeyVersionRequest', + 'UpdateCryptoKeyPrimaryVersionRequest', + 'UpdateCryptoKeyRequest', + 'UpdateCryptoKeyVersionRequest', +) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey.py new file mode 100644 index 000000000000..42fcb9aaec75 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey.py @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.kms.v1', + manifest={ + 'CreateKeyHandleRequest', + 'GetKeyHandleRequest', + 'KeyHandle', + 'CreateKeyHandleMetadata', + 'ListKeyHandlesRequest', + 'ListKeyHandlesResponse', + }, +) + + +class CreateKeyHandleRequest(proto.Message): + r"""Request message for + [Autokey.CreateKeyHandle][google.cloud.kms.v1.Autokey.CreateKeyHandle]. + + Attributes: + parent (str): + Required. Name of the resource project and location to + create the [KeyHandle][google.cloud.kms.v1.KeyHandle] in, + e.g. ``projects/{PROJECT_ID}/locations/{LOCATION}``. + key_handle_id (str): + Optional. Id of the + [KeyHandle][google.cloud.kms.v1.KeyHandle]. Must be unique + to the resource project and location. If not provided by the + caller, a new UUID is used. + key_handle (google.cloud.kms_v1.types.KeyHandle): + Required. [KeyHandle][google.cloud.kms.v1.KeyHandle] to + create. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + key_handle_id: str = proto.Field( + proto.STRING, + number=2, + ) + key_handle: 'KeyHandle' = proto.Field( + proto.MESSAGE, + number=3, + message='KeyHandle', + ) + + +class GetKeyHandleRequest(proto.Message): + r"""Request message for + [GetKeyHandle][google.cloud.kms.v1.Autokey.GetKeyHandle]. + + Attributes: + name (str): + Required. Name of the + [KeyHandle][google.cloud.kms.v1.KeyHandle] resource, e.g. + ``projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class KeyHandle(proto.Message): + r"""Resource-oriented representation of a request to Cloud KMS Autokey + and the resulting provisioning of a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Attributes: + name (str): + Identifier. Name of the + [KeyHandle][google.cloud.kms.v1.KeyHandle] resource, e.g. + ``projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}``. + kms_key (str): + Output only. Name of a + [CryptoKey][google.cloud.kms.v1.CryptoKey] that has been + provisioned for Customer Managed Encryption Key (CMEK) use + in the [KeyHandle][google.cloud.kms.v1.KeyHandle] project + and location for the requested resource type. The + [CryptoKey][google.cloud.kms.v1.CryptoKey] project will + reflect the value configured in the + [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] on the + resource project's ancestor folder at the time of the + [KeyHandle][google.cloud.kms.v1.KeyHandle] creation. If more + than one ancestor folder has a configured + [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig], the + nearest of these configurations is used. + resource_type_selector (str): + Required. Indicates the resource type that the resulting + [CryptoKey][google.cloud.kms.v1.CryptoKey] is meant to + protect, e.g. ``{SERVICE}.googleapis.com/{TYPE}``. See + documentation for supported resource types. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + kms_key: str = proto.Field( + proto.STRING, + number=3, + ) + resource_type_selector: str = proto.Field( + proto.STRING, + number=4, + ) + + +class CreateKeyHandleMetadata(proto.Message): + r"""Metadata message for + [CreateKeyHandle][google.cloud.kms.v1.Autokey.CreateKeyHandle] + long-running operation response. + + """ + + +class ListKeyHandlesRequest(proto.Message): + r"""Request message for + [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. + + Attributes: + parent (str): + Required. Name of the resource project and location from + which to list [KeyHandles][google.cloud.kms.v1.KeyHandle], + e.g. ``projects/{PROJECT_ID}/locations/{LOCATION}``. + page_size (int): + Optional. Optional limit on the number of + [KeyHandles][google.cloud.kms.v1.KeyHandle] to include in + the response. The service may return fewer than this value. + Further [KeyHandles][google.cloud.kms.v1.KeyHandle] can + subsequently be obtained by including the + [ListKeyHandlesResponse.next_page_token][google.cloud.kms.v1.ListKeyHandlesResponse.next_page_token] + in a subsequent request. If unspecified, at most 100 + [KeyHandles][google.cloud.kms.v1.KeyHandle] will be + returned. + page_token (str): + Optional. Optional pagination token, returned earlier via + [ListKeyHandlesResponse.next_page_token][google.cloud.kms.v1.ListKeyHandlesResponse.next_page_token]. + filter (str): + Optional. Filter to apply when listing + [KeyHandles][google.cloud.kms.v1.KeyHandle], e.g. + ``resource_type_selector="{SERVICE}.googleapis.com/{TYPE}"``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListKeyHandlesResponse(proto.Message): + r"""Response message for + [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. + + Attributes: + key_handles (MutableSequence[google.cloud.kms_v1.types.KeyHandle]): + Resulting [KeyHandles][google.cloud.kms.v1.KeyHandle]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListKeyHandlesRequest.page_token][google.cloud.kms.v1.ListKeyHandlesRequest.page_token] + to retrieve the next page of results. + """ + + @property + def raw_page(self): + return self + + key_handles: MutableSequence['KeyHandle'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='KeyHandle', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey_admin.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey_admin.py new file mode 100644 index 000000000000..1c7ec9aaa444 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey_admin.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 + + +__protobuf__ = proto.module( + package='google.cloud.kms.v1', + manifest={ + 'UpdateAutokeyConfigRequest', + 'GetAutokeyConfigRequest', + 'AutokeyConfig', + 'ShowEffectiveAutokeyConfigRequest', + 'ShowEffectiveAutokeyConfigResponse', + }, +) + + +class UpdateAutokeyConfigRequest(proto.Message): + r"""Request message for + [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig]. + + Attributes: + autokey_config (google.cloud.kms_v1.types.AutokeyConfig): + Required. [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] + with values to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. Masks which fields of the + [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] to + update, e.g. ``keyProject``. + """ + + autokey_config: 'AutokeyConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='AutokeyConfig', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetAutokeyConfigRequest(proto.Message): + r"""Request message for + [GetAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig]. + + Attributes: + name (str): + Required. Name of the + [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] resource, + e.g. ``folders/{FOLDER_NUMBER}/autokeyConfig``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AutokeyConfig(proto.Message): + r"""Cloud KMS Autokey configuration for a folder. + + Attributes: + name (str): + Identifier. Name of the + [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] resource, + e.g. ``folders/{FOLDER_NUMBER}/autokeyConfig``. + key_project (str): + Optional. Name of the key project, e.g. + ``projects/{PROJECT_ID}`` or ``projects/{PROJECT_NUMBER}``, + where Cloud KMS Autokey will provision a new + [CryptoKey][google.cloud.kms.v1.CryptoKey] when a + [KeyHandle][google.cloud.kms.v1.KeyHandle] is created. On + [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig], + the caller will require ``cloudkms.cryptoKeys.setIamPolicy`` + permission on this key project. Once configured, for Cloud + KMS Autokey to function properly, this key project must have + the Cloud KMS API activated and the Cloud KMS Service Agent + for this key project must be granted the ``cloudkms.admin`` + role (or pertinent permissions). A request with an empty key + project field will clear the configuration. + state (google.cloud.kms_v1.types.AutokeyConfig.State): + Output only. The state for the AutokeyConfig. + """ + class State(proto.Enum): + r"""The states AutokeyConfig can be in. + + Values: + STATE_UNSPECIFIED (0): + The state of the AutokeyConfig is + unspecified. + ACTIVE (1): + The AutokeyConfig is currently active. + KEY_PROJECT_DELETED (2): + A previously configured key project has been + deleted and the current AutokeyConfig is + unusable. + UNINITIALIZED (3): + The AutokeyConfig is not yet initialized or + has been reset to its default uninitialized + state. + """ + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + KEY_PROJECT_DELETED = 2 + UNINITIALIZED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + key_project: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + + +class ShowEffectiveAutokeyConfigRequest(proto.Message): + r"""Request message for + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + + Attributes: + parent (str): + Required. Name of the resource project to the + show effective Cloud KMS Autokey configuration + for. This may be helpful for interrogating the + effect of nested folder configurations on a + given resource project. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ShowEffectiveAutokeyConfigResponse(proto.Message): + r"""Response message for + [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. + + Attributes: + key_project (str): + Name of the key project configured in the + resource project's folder ancestry. + """ + + key_project: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/ekm_service.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/ekm_service.py new file mode 100644 index 000000000000..3db4aba34db2 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/ekm_service.py @@ -0,0 +1,554 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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.kms.v1', + manifest={ + 'ListEkmConnectionsRequest', + 'ListEkmConnectionsResponse', + 'GetEkmConnectionRequest', + 'CreateEkmConnectionRequest', + 'UpdateEkmConnectionRequest', + 'GetEkmConfigRequest', + 'UpdateEkmConfigRequest', + 'Certificate', + 'EkmConnection', + 'EkmConfig', + 'VerifyConnectivityRequest', + 'VerifyConnectivityResponse', + }, +) + + +class ListEkmConnectionsRequest(proto.Message): + r"""Request message for + [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the [EkmConnections][google.cloud.kms.v1.EkmConnection] to + list, in the format ``projects/*/locations/*``. + page_size (int): + Optional. Optional limit on the number of + [EkmConnections][google.cloud.kms.v1.EkmConnection] to + include in the response. Further + [EkmConnections][google.cloud.kms.v1.EkmConnection] can + subsequently be obtained by including the + [ListEkmConnectionsResponse.next_page_token][google.cloud.kms.v1.ListEkmConnectionsResponse.next_page_token] + in a subsequent request. If unspecified, the server will + pick an appropriate default. + page_token (str): + Optional. Optional pagination token, returned earlier via + [ListEkmConnectionsResponse.next_page_token][google.cloud.kms.v1.ListEkmConnectionsResponse.next_page_token]. + filter (str): + Optional. Only include resources that match the filter in + the response. For more information, see `Sorting and + filtering list + results `__. + order_by (str): + Optional. Specify how the results should be sorted. If not + specified, the results will be sorted in the default order. + For more information, see `Sorting and filtering list + results `__. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListEkmConnectionsResponse(proto.Message): + r"""Response message for + [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. + + Attributes: + ekm_connections (MutableSequence[google.cloud.kms_v1.types.EkmConnection]): + The list of + [EkmConnections][google.cloud.kms.v1.EkmConnection]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListEkmConnectionsRequest.page_token][google.cloud.kms.v1.ListEkmConnectionsRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of + [EkmConnections][google.cloud.kms.v1.EkmConnection] that + matched the query. + """ + + @property + def raw_page(self): + return self + + ekm_connections: MutableSequence['EkmConnection'] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message='EkmConnection', + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class GetEkmConnectionRequest(proto.Message): + r"""Request message for + [EkmService.GetEkmConnection][google.cloud.kms.v1.EkmService.GetEkmConnection]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.EkmConnection.name] + of the [EkmConnection][google.cloud.kms.v1.EkmConnection] to + get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateEkmConnectionRequest(proto.Message): + r"""Request message for + [EkmService.CreateEkmConnection][google.cloud.kms.v1.EkmService.CreateEkmConnection]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the [EkmConnection][google.cloud.kms.v1.EkmConnection], in + the format ``projects/*/locations/*``. + ekm_connection_id (str): + Required. It must be unique within a location and match the + regular expression ``[a-zA-Z0-9_-]{1,63}``. + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. An + [EkmConnection][google.cloud.kms.v1.EkmConnection] with + initial field values. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + ekm_connection_id: str = proto.Field( + proto.STRING, + number=2, + ) + ekm_connection: 'EkmConnection' = proto.Field( + proto.MESSAGE, + number=3, + message='EkmConnection', + ) + + +class UpdateEkmConnectionRequest(proto.Message): + r"""Request message for + [EkmService.UpdateEkmConnection][google.cloud.kms.v1.EkmService.UpdateEkmConnection]. + + Attributes: + ekm_connection (google.cloud.kms_v1.types.EkmConnection): + Required. [EkmConnection][google.cloud.kms.v1.EkmConnection] + with updated values. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + ekm_connection: 'EkmConnection' = proto.Field( + proto.MESSAGE, + number=1, + message='EkmConnection', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class GetEkmConfigRequest(proto.Message): + r"""Request message for + [EkmService.GetEkmConfig][google.cloud.kms.v1.EkmService.GetEkmConfig]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.EkmConfig.name] of + the [EkmConfig][google.cloud.kms.v1.EkmConfig] to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateEkmConfigRequest(proto.Message): + r"""Request message for + [EkmService.UpdateEkmConfig][google.cloud.kms.v1.EkmService.UpdateEkmConfig]. + + Attributes: + ekm_config (google.cloud.kms_v1.types.EkmConfig): + Required. [EkmConfig][google.cloud.kms.v1.EkmConfig] with + updated values. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + ekm_config: 'EkmConfig' = proto.Field( + proto.MESSAGE, + number=1, + message='EkmConfig', + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class Certificate(proto.Message): + r"""A [Certificate][google.cloud.kms.v1.Certificate] represents an X.509 + certificate used to authenticate HTTPS connections to EKM replicas. + + Attributes: + raw_der (bytes): + Required. The raw certificate bytes in DER + format. + parsed (bool): + Output only. True if the certificate was + parsed successfully. + issuer (str): + Output only. The issuer distinguished name in RFC 2253 + format. Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + subject (str): + Output only. The subject distinguished name in RFC 2253 + format. Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + subject_alternative_dns_names (MutableSequence[str]): + Output only. The subject Alternative DNS names. Only present + if [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + not_before_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The certificate is not valid before this time. + Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + not_after_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The certificate is not valid after this time. + Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + serial_number (str): + Output only. The certificate serial number as a hex string. + Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + sha256_fingerprint (str): + Output only. The SHA-256 certificate fingerprint as a hex + string. Only present if + [parsed][google.cloud.kms.v1.Certificate.parsed] is true. + """ + + raw_der: bytes = proto.Field( + proto.BYTES, + number=1, + ) + parsed: bool = proto.Field( + proto.BOOL, + number=2, + ) + issuer: str = proto.Field( + proto.STRING, + number=3, + ) + subject: str = proto.Field( + proto.STRING, + number=4, + ) + subject_alternative_dns_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + not_before_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + not_after_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + serial_number: str = proto.Field( + proto.STRING, + number=8, + ) + sha256_fingerprint: str = proto.Field( + proto.STRING, + number=9, + ) + + +class EkmConnection(proto.Message): + r"""An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an + individual EKM connection. It can be used for creating + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], as + well as performing cryptographic operations using keys created + within the [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Attributes: + name (str): + Output only. The resource name for the + [EkmConnection][google.cloud.kms.v1.EkmConnection] in the + format ``projects/*/locations/*/ekmConnections/*``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which the + [EkmConnection][google.cloud.kms.v1.EkmConnection] was + created. + service_resolvers (MutableSequence[google.cloud.kms_v1.types.EkmConnection.ServiceResolver]): + Optional. A list of + [ServiceResolvers][google.cloud.kms.v1.EkmConnection.ServiceResolver] + where the EKM can be reached. There should be one + ServiceResolver per EKM replica. Currently, only a single + [ServiceResolver][google.cloud.kms.v1.EkmConnection.ServiceResolver] + is supported. + etag (str): + Optional. Etag of the currently stored + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + key_management_mode (google.cloud.kms_v1.types.EkmConnection.KeyManagementMode): + Optional. Describes who can perform control plane operations + on the EKM. If unset, this defaults to + [MANUAL][google.cloud.kms.v1.EkmConnection.KeyManagementMode.MANUAL]. + crypto_space_path (str): + Optional. Identifies the EKM Crypto Space that this + [EkmConnection][google.cloud.kms.v1.EkmConnection] maps to. + Note: This field is required if + [KeyManagementMode][google.cloud.kms.v1.EkmConnection.KeyManagementMode] + is + [CLOUD_KMS][google.cloud.kms.v1.EkmConnection.KeyManagementMode.CLOUD_KMS]. + """ + class KeyManagementMode(proto.Enum): + r"""[KeyManagementMode][google.cloud.kms.v1.EkmConnection.KeyManagementMode] + describes who can perform control plane cryptographic operations + using this [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Values: + KEY_MANAGEMENT_MODE_UNSPECIFIED (0): + Not specified. + MANUAL (1): + EKM-side key management operations on + [CryptoKeys][google.cloud.kms.v1.CryptoKey] created with + this [EkmConnection][google.cloud.kms.v1.EkmConnection] must + be initiated from the EKM directly and cannot be performed + from Cloud KMS. This means that: + + - When creating a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + associated with this + [EkmConnection][google.cloud.kms.v1.EkmConnection], the + caller must supply the key path of pre-existing external + key material that will be linked to the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + - Destruction of external key material cannot be requested + via the Cloud KMS API and must be performed directly in + the EKM. + - Automatic rotation of key material is not supported. + CLOUD_KMS (2): + All [CryptoKeys][google.cloud.kms.v1.CryptoKey] created with + this [EkmConnection][google.cloud.kms.v1.EkmConnection] use + EKM-side key management operations initiated from Cloud KMS. + This means that: + + - When a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + associated with this + [EkmConnection][google.cloud.kms.v1.EkmConnection] is + created, the EKM automatically generates new key material + and a new key path. The caller cannot supply the key path + of pre-existing external key material. + - Destruction of external key material associated with this + [EkmConnection][google.cloud.kms.v1.EkmConnection] can be + requested by calling + [DestroyCryptoKeyVersion][EkmService.DestroyCryptoKeyVersion]. + - Automatic rotation of key material is supported. + """ + KEY_MANAGEMENT_MODE_UNSPECIFIED = 0 + MANUAL = 1 + CLOUD_KMS = 2 + + class ServiceResolver(proto.Message): + r"""A + [ServiceResolver][google.cloud.kms.v1.EkmConnection.ServiceResolver] + represents an EKM replica that can be reached within an + [EkmConnection][google.cloud.kms.v1.EkmConnection]. + + Attributes: + service_directory_service (str): + Required. The resource name of the Service Directory service + pointing to an EKM replica, in the format + ``projects/*/locations/*/namespaces/*/services/*``. + endpoint_filter (str): + Optional. The filter applied to the endpoints + of the resolved service. If no filter is + specified, all endpoints will be considered. An + endpoint will be chosen arbitrarily from the + filtered list for each request. + + For endpoint filter syntax and examples, see + https://cloud.google.com/service-directory/docs/reference/rpc/google.cloud.servicedirectory.v1#resolveservicerequest. + hostname (str): + Required. The hostname of the EKM replica + used at TLS and HTTP layers. + server_certificates (MutableSequence[google.cloud.kms_v1.types.Certificate]): + Required. A list of leaf server certificates used to + authenticate HTTPS connections to the EKM replica. + Currently, a maximum of 10 + [Certificate][google.cloud.kms.v1.Certificate] is supported. + """ + + service_directory_service: str = proto.Field( + proto.STRING, + number=1, + ) + endpoint_filter: str = proto.Field( + proto.STRING, + number=2, + ) + hostname: str = proto.Field( + proto.STRING, + number=3, + ) + server_certificates: MutableSequence['Certificate'] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message='Certificate', + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + service_resolvers: MutableSequence[ServiceResolver] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ServiceResolver, + ) + etag: str = proto.Field( + proto.STRING, + number=5, + ) + key_management_mode: KeyManagementMode = proto.Field( + proto.ENUM, + number=6, + enum=KeyManagementMode, + ) + crypto_space_path: str = proto.Field( + proto.STRING, + number=7, + ) + + +class EkmConfig(proto.Message): + r"""An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a singleton + resource that represents configuration parameters that apply to all + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] with a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] in a + given project and location. + + Attributes: + name (str): + Output only. The resource name for the + [EkmConfig][google.cloud.kms.v1.EkmConfig] in the format + ``projects/*/locations/*/ekmConfig``. + default_ekm_connection (str): + Optional. Resource name of the default + [EkmConnection][google.cloud.kms.v1.EkmConnection]. Setting + this field to the empty string removes the default. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + default_ekm_connection: str = proto.Field( + proto.STRING, + number=2, + ) + + +class VerifyConnectivityRequest(proto.Message): + r"""Request message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.EkmConnection.name] + of the [EkmConnection][google.cloud.kms.v1.EkmConnection] to + verify. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class VerifyConnectivityResponse(proto.Message): + r"""Response message for + [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. + + """ + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/resources.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/resources.py new file mode 100644 index 000000000000..090a67f7938c --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/resources.py @@ -0,0 +1,1383 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES 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 duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.kms.v1', + manifest={ + 'ProtectionLevel', + 'AccessReason', + 'KeyRing', + 'CryptoKey', + 'CryptoKeyVersionTemplate', + 'KeyOperationAttestation', + 'CryptoKeyVersion', + 'PublicKey', + 'ImportJob', + 'ExternalProtectionLevelOptions', + 'KeyAccessJustificationsPolicy', + }, +) + + +class ProtectionLevel(proto.Enum): + r"""[ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] specifies how + cryptographic operations are performed. For more information, see + [Protection levels] + (https://cloud.google.com/kms/docs/algorithms#protection_levels). + + Values: + PROTECTION_LEVEL_UNSPECIFIED (0): + Not specified. + SOFTWARE (1): + Crypto operations are performed in software. + HSM (2): + Crypto operations are performed in a Hardware + Security Module. + EXTERNAL (3): + Crypto operations are performed by an + external key manager. + EXTERNAL_VPC (4): + Crypto operations are performed in an + EKM-over-VPC backend. + """ + PROTECTION_LEVEL_UNSPECIFIED = 0 + SOFTWARE = 1 + HSM = 2 + EXTERNAL = 3 + EXTERNAL_VPC = 4 + + +class AccessReason(proto.Enum): + r"""Describes the reason for a data access. Please refer to + https://cloud.google.com/assured-workloads/key-access-justifications/docs/justification-codes + for the detailed semantic meaning of justification reason codes. + + Values: + REASON_UNSPECIFIED (0): + Unspecified access reason. + CUSTOMER_INITIATED_SUPPORT (1): + Customer-initiated support. + GOOGLE_INITIATED_SERVICE (2): + Google-initiated access for system management + and troubleshooting. + THIRD_PARTY_DATA_REQUEST (3): + Google-initiated access in response to a + legal request or legal process. + GOOGLE_INITIATED_REVIEW (4): + Google-initiated access for security, fraud, + abuse, or compliance purposes. + CUSTOMER_INITIATED_ACCESS (5): + Customer uses their account to perform any + access to their own data which their IAM policy + authorizes. + GOOGLE_INITIATED_SYSTEM_OPERATION (6): + Google systems access customer data to help + optimize the structure of the data or quality + for future uses by the customer. + REASON_NOT_EXPECTED (7): + No reason is expected for this key request. + MODIFIED_CUSTOMER_INITIATED_ACCESS (8): + Customer uses their account to perform any access to their + own data which their IAM policy authorizes, and one of the + following is true: + + - A Google administrator has reset the root-access account + associated with the user's organization within the past 7 + days. + - A Google-initiated emergency access operation has + interacted with a resource in the same project or folder + as the currently accessed resource within the past 7 + days. + MODIFIED_GOOGLE_INITIATED_SYSTEM_OPERATION (9): + Google systems access customer data to help optimize the + structure of the data or quality for future uses by the + customer, and one of the following is true: + + - A Google administrator has reset the root-access account + associated with the user's organization within the past 7 + days. + - A Google-initiated emergency access operation has + interacted with a resource in the same project or folder + as the currently accessed resource within the past 7 + days. + GOOGLE_RESPONSE_TO_PRODUCTION_ALERT (10): + Google-initiated access to maintain system + reliability. + CUSTOMER_AUTHORIZED_WORKFLOW_SERVICING (11): + One of the following operations is being executed while + simultaneously encountering an internal technical issue + which prevented a more precise justification code from being + generated: + + - Your account has been used to perform any access to your + own data which your IAM policy authorizes. + - An automated Google system operates on encrypted customer + data which your IAM policy authorizes. + - Customer-initiated Google support access. + - Google-initiated support access to protect system + reliability. + """ + REASON_UNSPECIFIED = 0 + CUSTOMER_INITIATED_SUPPORT = 1 + GOOGLE_INITIATED_SERVICE = 2 + THIRD_PARTY_DATA_REQUEST = 3 + GOOGLE_INITIATED_REVIEW = 4 + CUSTOMER_INITIATED_ACCESS = 5 + GOOGLE_INITIATED_SYSTEM_OPERATION = 6 + REASON_NOT_EXPECTED = 7 + MODIFIED_CUSTOMER_INITIATED_ACCESS = 8 + MODIFIED_GOOGLE_INITIATED_SYSTEM_OPERATION = 9 + GOOGLE_RESPONSE_TO_PRODUCTION_ALERT = 10 + CUSTOMER_AUTHORIZED_WORKFLOW_SERVICING = 11 + + +class KeyRing(proto.Message): + r"""A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical + grouping of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + + Attributes: + name (str): + Output only. The resource name for the + [KeyRing][google.cloud.kms.v1.KeyRing] in the format + ``projects/*/locations/*/keyRings/*``. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [KeyRing][google.cloud.kms.v1.KeyRing] was created. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class CryptoKey(proto.Message): + r"""A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical + key that can be used for cryptographic operations. + + A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or + more [versions][google.cloud.kms.v1.CryptoKeyVersion], which + represent the actual key material used in cryptographic operations. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. The resource name for this + [CryptoKey][google.cloud.kms.v1.CryptoKey] in the format + ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + primary (google.cloud.kms_v1.types.CryptoKeyVersion): + Output only. A copy of the "primary" + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + that will be used by + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] + when this [CryptoKey][google.cloud.kms.v1.CryptoKey] is + given in + [EncryptRequest.name][google.cloud.kms.v1.EncryptRequest.name]. + + The [CryptoKey][google.cloud.kms.v1.CryptoKey]'s primary + version can be updated via + [UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. + + Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] + may have a primary. For other keys, this field will be + omitted. + purpose (google.cloud.kms_v1.types.CryptoKey.CryptoKeyPurpose): + Immutable. The immutable purpose of this + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [CryptoKey][google.cloud.kms.v1.CryptoKey] was created. + next_rotation_time (google.protobuf.timestamp_pb2.Timestamp): + At + [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time], + the Key Management Service will automatically: + + 1. Create a new version of this + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + 2. Mark the new version as primary. + + Key rotations performed manually via + [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] + and + [UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion] + do not affect + [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time]. + + Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] + support automatic rotation. For other keys, this field must + be omitted. + rotation_period (google.protobuf.duration_pb2.Duration): + [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time] + will be advanced by this period when the service + automatically rotates a key. Must be at least 24 hours and + at most 876,000 hours. + + If + [rotation_period][google.cloud.kms.v1.CryptoKey.rotation_period] + is set, + [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time] + must also be set. + + Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] + support automatic rotation. For other keys, this field must + be omitted. + + This field is a member of `oneof`_ ``rotation_schedule``. + version_template (google.cloud.kms_v1.types.CryptoKeyVersionTemplate): + A template describing settings for new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + instances. The properties of new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + instances created by either + [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] + or auto-rotation are controlled by this template. + labels (MutableMapping[str, str]): + Labels with user-defined metadata. For more information, see + `Labeling + Keys `__. + import_only (bool): + Immutable. Whether this key may contain + imported versions only. + destroy_scheduled_duration (google.protobuf.duration_pb2.Duration): + Immutable. The period of time that versions of this key + spend in the + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] + state before transitioning to + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED]. + If not specified at creation time, the default duration is + 30 days. + crypto_key_backend (str): + Immutable. The resource name of the backend environment + where the key material for all + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + associated with this + [CryptoKey][google.cloud.kms.v1.CryptoKey] reside and where + all related cryptographic operations are performed. Only + applicable if + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + have a + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of + [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], + with the resource name in the format + ``projects/*/locations/*/ekmConnections/*``. Note, this list + is non-exhaustive and may apply to additional + [ProtectionLevels][google.cloud.kms.v1.ProtectionLevel] in + the future. + key_access_justifications_policy (google.cloud.kms_v1.types.KeyAccessJustificationsPolicy): + Optional. The policy used for Key Access + Justifications Policy Enforcement. If this field + is present and this key is enrolled in Key + Access Justifications Policy Enforcement, the + policy will be evaluated in encrypt, decrypt, + and sign operations, and the operation will fail + if rejected by the policy. The policy is defined + by specifying zero or more allowed justification + codes. + https://cloud.google.com/assured-workloads/key-access-justifications/docs/justification-codes + By default, this field is absent, and all + justification codes are allowed. + """ + class CryptoKeyPurpose(proto.Enum): + r"""[CryptoKeyPurpose][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose] + describes the cryptographic capabilities of a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. A given key can only be + used for the operations allowed by its purpose. For more + information, see `Key + purposes `__. + + Values: + CRYPTO_KEY_PURPOSE_UNSPECIFIED (0): + Not specified. + ENCRYPT_DECRYPT (1): + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this + purpose may be used with + [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] + and + [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + ASYMMETRIC_SIGN (5): + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this + purpose may be used with + [AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign] + and + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + ASYMMETRIC_DECRYPT (6): + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this + purpose may be used with + [AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt] + and + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + RAW_ENCRYPT_DECRYPT (7): + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this + purpose may be used with + [RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt] + and + [RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. + This purpose is meant to be used for interoperable symmetric + encryption and does not support automatic CryptoKey + rotation. + MAC (9): + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this + purpose may be used with + [MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + """ + CRYPTO_KEY_PURPOSE_UNSPECIFIED = 0 + ENCRYPT_DECRYPT = 1 + ASYMMETRIC_SIGN = 5 + ASYMMETRIC_DECRYPT = 6 + RAW_ENCRYPT_DECRYPT = 7 + MAC = 9 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + primary: 'CryptoKeyVersion' = proto.Field( + proto.MESSAGE, + number=2, + message='CryptoKeyVersion', + ) + purpose: CryptoKeyPurpose = proto.Field( + proto.ENUM, + number=3, + enum=CryptoKeyPurpose, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + next_rotation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + rotation_period: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + oneof='rotation_schedule', + message=duration_pb2.Duration, + ) + version_template: 'CryptoKeyVersionTemplate' = proto.Field( + proto.MESSAGE, + number=11, + message='CryptoKeyVersionTemplate', + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=10, + ) + import_only: bool = proto.Field( + proto.BOOL, + number=13, + ) + destroy_scheduled_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=14, + message=duration_pb2.Duration, + ) + crypto_key_backend: str = proto.Field( + proto.STRING, + number=15, + ) + key_access_justifications_policy: 'KeyAccessJustificationsPolicy' = proto.Field( + proto.MESSAGE, + number=17, + message='KeyAccessJustificationsPolicy', + ) + + +class CryptoKeyVersionTemplate(proto.Message): + r"""A + [CryptoKeyVersionTemplate][google.cloud.kms.v1.CryptoKeyVersionTemplate] + specifies the properties to use when creating a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], either + manually with + [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] + or automatically as a result of auto-rotation. + + Attributes: + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] to + use when creating a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + based on this template. Immutable. Defaults to + [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE]. + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + Required. + [Algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] + to use when creating a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + based on this template. + + For backwards compatibility, GOOGLE_SYMMETRIC_ENCRYPTION is + implied if both this field is omitted and + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + is + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + """ + + protection_level: 'ProtectionLevel' = proto.Field( + proto.ENUM, + number=1, + enum='ProtectionLevel', + ) + algorithm: 'CryptoKeyVersion.CryptoKeyVersionAlgorithm' = proto.Field( + proto.ENUM, + number=3, + enum='CryptoKeyVersion.CryptoKeyVersionAlgorithm', + ) + + +class KeyOperationAttestation(proto.Message): + r"""Contains an HSM-generated attestation about a key operation. For + more information, see [Verifying attestations] + (https://cloud.google.com/kms/docs/attest-key). + + Attributes: + format_ (google.cloud.kms_v1.types.KeyOperationAttestation.AttestationFormat): + Output only. The format of the attestation + data. + content (bytes): + Output only. The attestation data provided by + the HSM when the key operation was performed. + cert_chains (google.cloud.kms_v1.types.KeyOperationAttestation.CertificateChains): + Output only. The certificate chains needed to + validate the attestation + """ + class AttestationFormat(proto.Enum): + r"""Attestation formats provided by the HSM. + + Values: + ATTESTATION_FORMAT_UNSPECIFIED (0): + Not specified. + CAVIUM_V1_COMPRESSED (3): + Cavium HSM attestation compressed with gzip. + Note that this format is defined by Cavium and + subject to change at any time. + + See + https://www.marvell.com/products/security-solutions/nitrox-hs-adapters/software-key-attestation.html. + CAVIUM_V2_COMPRESSED (4): + Cavium HSM attestation V2 compressed with + gzip. This is a new format introduced in + Cavium's version 3.2-08. + """ + ATTESTATION_FORMAT_UNSPECIFIED = 0 + CAVIUM_V1_COMPRESSED = 3 + CAVIUM_V2_COMPRESSED = 4 + + class CertificateChains(proto.Message): + r"""Certificate chains needed to verify the attestation. + Certificates in chains are PEM-encoded and are ordered based on + https://tools.ietf.org/html/rfc5246#section-7.4.2. + + Attributes: + cavium_certs (MutableSequence[str]): + Cavium certificate chain corresponding to the + attestation. + google_card_certs (MutableSequence[str]): + Google card certificate chain corresponding + to the attestation. + google_partition_certs (MutableSequence[str]): + Google partition certificate chain + corresponding to the attestation. + """ + + cavium_certs: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + google_card_certs: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + google_partition_certs: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + format_: AttestationFormat = proto.Field( + proto.ENUM, + number=4, + enum=AttestationFormat, + ) + content: bytes = proto.Field( + proto.BYTES, + number=5, + ) + cert_chains: CertificateChains = proto.Field( + proto.MESSAGE, + number=6, + message=CertificateChains, + ) + + +class CryptoKeyVersion(proto.Message): + r"""A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material represented + by a [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] can + never be viewed or exported. It can only be used to encrypt, + decrypt, or sign data when an authorized user or application invokes + Cloud KMS. + + Attributes: + name (str): + Output only. The resource name for this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in + the format + ``projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*``. + state (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionState): + The current state of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + Output only. The + [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + describing how crypto operations are performed with this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + Output only. The + [CryptoKeyVersionAlgorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] + that this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + supports. + attestation (google.cloud.kms_v1.types.KeyOperationAttestation): + Output only. Statement that was generated and signed by the + HSM at key creation time. Use this statement to verify + attributes of the key as stored on the HSM, independently of + Google. Only provided for key versions with + [protection_level][google.cloud.kms.v1.CryptoKeyVersion.protection_level] + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM]. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] was + created. + generate_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + key material was generated. + destroy_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + key material is scheduled for destruction. Only present if + [state][google.cloud.kms.v1.CryptoKeyVersion.state] is + [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED]. + destroy_event_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this CryptoKeyVersion's key material + was destroyed. Only present if + [state][google.cloud.kms.v1.CryptoKeyVersion.state] is + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED]. + import_job (str): + Output only. The name of the + [ImportJob][google.cloud.kms.v1.ImportJob] used in the most + recent import of this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + Only present if the underlying key material was imported. + import_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + key material was most recently imported. + import_failure_reason (str): + Output only. The root cause of the most recent import + failure. Only present if + [state][google.cloud.kms.v1.CryptoKeyVersion.state] is + [IMPORT_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.IMPORT_FAILED]. + generation_failure_reason (str): + Output only. The root cause of the most recent generation + failure. Only present if + [state][google.cloud.kms.v1.CryptoKeyVersion.state] is + [GENERATION_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.GENERATION_FAILED]. + external_destruction_failure_reason (str): + Output only. The root cause of the most recent external + destruction failure. Only present if + [state][google.cloud.kms.v1.CryptoKeyVersion.state] is + [EXTERNAL_DESTRUCTION_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.EXTERNAL_DESTRUCTION_FAILED]. + external_protection_level_options (google.cloud.kms_v1.types.ExternalProtectionLevelOptions): + ExternalProtectionLevelOptions stores a group of additional + fields for configuring a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + that are specific to the + [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] + protection level and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + protection levels. + reimport_eligible (bool): + Output only. Whether or not this key version is eligible for + reimport, by being specified as a target in + [ImportCryptoKeyVersionRequest.crypto_key_version][google.cloud.kms.v1.ImportCryptoKeyVersionRequest.crypto_key_version]. + """ + class CryptoKeyVersionAlgorithm(proto.Enum): + r"""The algorithm of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], indicating + what parameters must be used for each cryptographic operation. + + The + [GOOGLE_SYMMETRIC_ENCRYPTION][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION] + algorithm is usable with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. + + Algorithms beginning with ``RSA_SIGN_`` are usable with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN]. + + The fields in the name after ``RSA_SIGN_`` correspond to the + following parameters: padding algorithm, modulus bit length, and + digest algorithm. + + For PSS, the salt length used is equal to the length of digest + algorithm. For example, + [RSA_SIGN_PSS_2048_SHA256][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_SIGN_PSS_2048_SHA256] + will use PSS with a salt length of 256 bits or 32 bytes. + + Algorithms beginning with ``RSA_DECRYPT_`` are usable with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. + + The fields in the name after ``RSA_DECRYPT_`` correspond to the + following parameters: padding algorithm, modulus bit length, and + digest algorithm. + + Algorithms beginning with ``EC_SIGN_`` are usable with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN]. + + The fields in the name after ``EC_SIGN_`` correspond to the + following parameters: elliptic curve, digest algorithm. + + Algorithms beginning with ``HMAC_`` are usable with + [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] + [MAC][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.MAC]. + + The suffix following ``HMAC_`` corresponds to the hash algorithm + being used (eg. SHA256). + + Algorithms beginning with ``PQ_`` are post-quantum. + + For more information, see [Key purposes and algorithms] + (https://cloud.google.com/kms/docs/algorithms). + + Values: + CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED (0): + Not specified. + GOOGLE_SYMMETRIC_ENCRYPTION (1): + Creates symmetric encryption keys. + AES_128_GCM (41): + AES-GCM (Galois Counter Mode) using 128-bit + keys. + AES_256_GCM (19): + AES-GCM (Galois Counter Mode) using 256-bit + keys. + AES_128_CBC (42): + AES-CBC (Cipher Block Chaining Mode) using + 128-bit keys. + AES_256_CBC (43): + AES-CBC (Cipher Block Chaining Mode) using + 256-bit keys. + AES_128_CTR (44): + AES-CTR (Counter Mode) using 128-bit keys. + AES_256_CTR (45): + AES-CTR (Counter Mode) using 256-bit keys. + RSA_SIGN_PSS_2048_SHA256 (2): + RSASSA-PSS 2048 bit key with a SHA256 digest. + RSA_SIGN_PSS_3072_SHA256 (3): + RSASSA-PSS 3072 bit key with a SHA256 digest. + RSA_SIGN_PSS_4096_SHA256 (4): + RSASSA-PSS 4096 bit key with a SHA256 digest. + RSA_SIGN_PSS_4096_SHA512 (15): + RSASSA-PSS 4096 bit key with a SHA512 digest. + RSA_SIGN_PKCS1_2048_SHA256 (5): + RSASSA-PKCS1-v1_5 with a 2048 bit key and a SHA256 digest. + RSA_SIGN_PKCS1_3072_SHA256 (6): + RSASSA-PKCS1-v1_5 with a 3072 bit key and a SHA256 digest. + RSA_SIGN_PKCS1_4096_SHA256 (7): + RSASSA-PKCS1-v1_5 with a 4096 bit key and a SHA256 digest. + RSA_SIGN_PKCS1_4096_SHA512 (16): + RSASSA-PKCS1-v1_5 with a 4096 bit key and a SHA512 digest. + RSA_SIGN_RAW_PKCS1_2048 (28): + RSASSA-PKCS1-v1_5 signing without encoding, with a 2048 bit + key. + RSA_SIGN_RAW_PKCS1_3072 (29): + RSASSA-PKCS1-v1_5 signing without encoding, with a 3072 bit + key. + RSA_SIGN_RAW_PKCS1_4096 (30): + RSASSA-PKCS1-v1_5 signing without encoding, with a 4096 bit + key. + RSA_DECRYPT_OAEP_2048_SHA256 (8): + RSAES-OAEP 2048 bit key with a SHA256 digest. + RSA_DECRYPT_OAEP_3072_SHA256 (9): + RSAES-OAEP 3072 bit key with a SHA256 digest. + RSA_DECRYPT_OAEP_4096_SHA256 (10): + RSAES-OAEP 4096 bit key with a SHA256 digest. + RSA_DECRYPT_OAEP_4096_SHA512 (17): + RSAES-OAEP 4096 bit key with a SHA512 digest. + RSA_DECRYPT_OAEP_2048_SHA1 (37): + RSAES-OAEP 2048 bit key with a SHA1 digest. + RSA_DECRYPT_OAEP_3072_SHA1 (38): + RSAES-OAEP 3072 bit key with a SHA1 digest. + RSA_DECRYPT_OAEP_4096_SHA1 (39): + RSAES-OAEP 4096 bit key with a SHA1 digest. + EC_SIGN_P256_SHA256 (12): + ECDSA on the NIST P-256 curve with a SHA256 digest. Other + hash functions can also be used: + https://cloud.google.com/kms/docs/create-validate-signatures#ecdsa_support_for_other_hash_algorithms + EC_SIGN_P384_SHA384 (13): + ECDSA on the NIST P-384 curve with a SHA384 digest. Other + hash functions can also be used: + https://cloud.google.com/kms/docs/create-validate-signatures#ecdsa_support_for_other_hash_algorithms + EC_SIGN_SECP256K1_SHA256 (31): + ECDSA on the non-NIST secp256k1 curve. This curve is only + supported for HSM protection level. Other hash functions can + also be used: + https://cloud.google.com/kms/docs/create-validate-signatures#ecdsa_support_for_other_hash_algorithms + EC_SIGN_ED25519 (40): + EdDSA on the Curve25519 in pure mode (taking + data as input). + HMAC_SHA256 (32): + HMAC-SHA256 signing with a 256 bit key. + HMAC_SHA1 (33): + HMAC-SHA1 signing with a 160 bit key. + HMAC_SHA384 (34): + HMAC-SHA384 signing with a 384 bit key. + HMAC_SHA512 (35): + HMAC-SHA512 signing with a 512 bit key. + HMAC_SHA224 (36): + HMAC-SHA224 signing with a 224 bit key. + EXTERNAL_SYMMETRIC_ENCRYPTION (18): + Algorithm representing symmetric encryption + by an external key manager. + """ + CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED = 0 + GOOGLE_SYMMETRIC_ENCRYPTION = 1 + AES_128_GCM = 41 + AES_256_GCM = 19 + AES_128_CBC = 42 + AES_256_CBC = 43 + AES_128_CTR = 44 + AES_256_CTR = 45 + RSA_SIGN_PSS_2048_SHA256 = 2 + RSA_SIGN_PSS_3072_SHA256 = 3 + RSA_SIGN_PSS_4096_SHA256 = 4 + RSA_SIGN_PSS_4096_SHA512 = 15 + RSA_SIGN_PKCS1_2048_SHA256 = 5 + RSA_SIGN_PKCS1_3072_SHA256 = 6 + RSA_SIGN_PKCS1_4096_SHA256 = 7 + RSA_SIGN_PKCS1_4096_SHA512 = 16 + RSA_SIGN_RAW_PKCS1_2048 = 28 + RSA_SIGN_RAW_PKCS1_3072 = 29 + RSA_SIGN_RAW_PKCS1_4096 = 30 + RSA_DECRYPT_OAEP_2048_SHA256 = 8 + RSA_DECRYPT_OAEP_3072_SHA256 = 9 + RSA_DECRYPT_OAEP_4096_SHA256 = 10 + RSA_DECRYPT_OAEP_4096_SHA512 = 17 + RSA_DECRYPT_OAEP_2048_SHA1 = 37 + RSA_DECRYPT_OAEP_3072_SHA1 = 38 + RSA_DECRYPT_OAEP_4096_SHA1 = 39 + EC_SIGN_P256_SHA256 = 12 + EC_SIGN_P384_SHA384 = 13 + EC_SIGN_SECP256K1_SHA256 = 31 + EC_SIGN_ED25519 = 40 + HMAC_SHA256 = 32 + HMAC_SHA1 = 33 + HMAC_SHA384 = 34 + HMAC_SHA512 = 35 + HMAC_SHA224 = 36 + EXTERNAL_SYMMETRIC_ENCRYPTION = 18 + + class CryptoKeyVersionState(proto.Enum): + r"""The state of a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], indicating + if it can be used. + + Values: + CRYPTO_KEY_VERSION_STATE_UNSPECIFIED (0): + Not specified. + PENDING_GENERATION (5): + This version is still being generated. It may not be used, + enabled, disabled, or destroyed yet. Cloud KMS will + automatically mark this version + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + as soon as the version is ready. + ENABLED (1): + This version may be used for cryptographic + operations. + DISABLED (2): + This version may not be used, but the key material is still + available, and the version can be placed back into the + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + state. + DESTROYED (3): + This version is destroyed, and the key material is no longer + stored. This version may only become + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + again if this version is + [reimport_eligible][google.cloud.kms.v1.CryptoKeyVersion.reimport_eligible] + and the original key material is reimported with a call to + [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + DESTROY_SCHEDULED (4): + This version is scheduled for destruction, and will be + destroyed soon. Call + [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + to put it back into the + [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] + state. + PENDING_IMPORT (6): + This version is still being imported. It may not be used, + enabled, disabled, or destroyed yet. Cloud KMS will + automatically mark this version + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + as soon as the version is ready. + IMPORT_FAILED (7): + This version was not imported successfully. It may not be + used, enabled, disabled, or destroyed. The submitted key + material has been discarded. Additional details can be found + in + [CryptoKeyVersion.import_failure_reason][google.cloud.kms.v1.CryptoKeyVersion.import_failure_reason]. + GENERATION_FAILED (8): + This version was not generated successfully. It may not be + used, enabled, disabled, or destroyed. Additional details + can be found in + [CryptoKeyVersion.generation_failure_reason][google.cloud.kms.v1.CryptoKeyVersion.generation_failure_reason]. + PENDING_EXTERNAL_DESTRUCTION (9): + This version was destroyed, and it may not be + used or enabled again. Cloud KMS is waiting for + the corresponding key material residing in an + external key manager to be destroyed. + EXTERNAL_DESTRUCTION_FAILED (10): + This version was destroyed, and it may not be used or + enabled again. However, Cloud KMS could not confirm that the + corresponding key material residing in an external key + manager was destroyed. Additional details can be found in + [CryptoKeyVersion.external_destruction_failure_reason][google.cloud.kms.v1.CryptoKeyVersion.external_destruction_failure_reason]. + """ + CRYPTO_KEY_VERSION_STATE_UNSPECIFIED = 0 + PENDING_GENERATION = 5 + ENABLED = 1 + DISABLED = 2 + DESTROYED = 3 + DESTROY_SCHEDULED = 4 + PENDING_IMPORT = 6 + IMPORT_FAILED = 7 + GENERATION_FAILED = 8 + PENDING_EXTERNAL_DESTRUCTION = 9 + EXTERNAL_DESTRUCTION_FAILED = 10 + + class CryptoKeyVersionView(proto.Enum): + r"""A view for + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]s. Controls + the level of detail returned for + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] in + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions] + and + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + Values: + CRYPTO_KEY_VERSION_VIEW_UNSPECIFIED (0): + Default view for each + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + Does not include the + [attestation][google.cloud.kms.v1.CryptoKeyVersion.attestation] + field. + FULL (1): + Provides all fields in each + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], + including the + [attestation][google.cloud.kms.v1.CryptoKeyVersion.attestation]. + """ + CRYPTO_KEY_VERSION_VIEW_UNSPECIFIED = 0 + FULL = 1 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: CryptoKeyVersionState = proto.Field( + proto.ENUM, + number=3, + enum=CryptoKeyVersionState, + ) + protection_level: 'ProtectionLevel' = proto.Field( + proto.ENUM, + number=7, + enum='ProtectionLevel', + ) + algorithm: CryptoKeyVersionAlgorithm = proto.Field( + proto.ENUM, + number=10, + enum=CryptoKeyVersionAlgorithm, + ) + attestation: 'KeyOperationAttestation' = proto.Field( + proto.MESSAGE, + number=8, + message='KeyOperationAttestation', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + generate_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + destroy_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + destroy_event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + import_job: str = proto.Field( + proto.STRING, + number=14, + ) + import_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=15, + message=timestamp_pb2.Timestamp, + ) + import_failure_reason: str = proto.Field( + proto.STRING, + number=16, + ) + generation_failure_reason: str = proto.Field( + proto.STRING, + number=19, + ) + external_destruction_failure_reason: str = proto.Field( + proto.STRING, + number=20, + ) + external_protection_level_options: 'ExternalProtectionLevelOptions' = proto.Field( + proto.MESSAGE, + number=17, + message='ExternalProtectionLevelOptions', + ) + reimport_eligible: bool = proto.Field( + proto.BOOL, + number=18, + ) + + +class PublicKey(proto.Message): + r"""The public keys for a given + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained + via + [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + Attributes: + pem (str): + The public key, encoded in PEM format. For more information, + see the `RFC 7468 `__ + sections for `General + Considerations `__ + and [Textual Encoding of Subject Public Key Info] + (https://tools.ietf.org/html/rfc7468#section-13). + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + The + [Algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] + associated with this key. + pem_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem]. + An integrity check of + [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem] can be + performed by computing the CRC32C checksum of + [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem] and + comparing your results to this field. Discard the response + in case of non-matching checksum values, and perform a + limited number of retries. A persistent mismatch may + indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + + NOTE: This field is in Beta. + name (str): + The [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + public key. Provided here for verification. + + NOTE: This field is in Beta. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + public key. + """ + + pem: str = proto.Field( + proto.STRING, + number=1, + ) + algorithm: 'CryptoKeyVersion.CryptoKeyVersionAlgorithm' = proto.Field( + proto.ENUM, + number=2, + enum='CryptoKeyVersion.CryptoKeyVersionAlgorithm', + ) + pem_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int64Value, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + protection_level: 'ProtectionLevel' = proto.Field( + proto.ENUM, + number=5, + enum='ProtectionLevel', + ) + + +class ImportJob(proto.Message): + r"""An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create + [CryptoKeys][google.cloud.kms.v1.CryptoKey] and + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] using + pre-existing key material, generated outside of Cloud KMS. + + When an [ImportJob][google.cloud.kms.v1.ImportJob] is created, Cloud + KMS will generate a "wrapping key", which is a public/private key + pair. You use the wrapping key to encrypt (also known as wrap) the + pre-existing key material to protect it during the import process. + The nature of the wrapping key depends on the choice of + [import_method][google.cloud.kms.v1.ImportJob.import_method]. When + the wrapping key generation is complete, the + [state][google.cloud.kms.v1.ImportJob.state] will be set to + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] and + the [public_key][google.cloud.kms.v1.ImportJob.public_key] can be + fetched. The fetched public key can then be used to wrap your + pre-existing key material. + + Once the key material is wrapped, it can be imported into a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in an + existing [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + Multiple [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can be imported with a single + [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS uses the + private key portion of the wrapping key to unwrap the key material. + Only Cloud KMS has access to the private key. + + An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 days after + it is created. Once expired, Cloud KMS will no longer be able to + import or unwrap any key material that was wrapped with the + [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. + + For more information, see `Importing a + key `__. + + Attributes: + name (str): + Output only. The resource name for this + [ImportJob][google.cloud.kms.v1.ImportJob] in the format + ``projects/*/locations/*/keyRings/*/importJobs/*``. + import_method (google.cloud.kms_v1.types.ImportJob.ImportMethod): + Required. Immutable. The wrapping method to + be used for incoming key material. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + Required. Immutable. The protection level of the + [ImportJob][google.cloud.kms.v1.ImportJob]. This must match + the + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] + of the + [version_template][google.cloud.kms.v1.CryptoKey.version_template] + on the [CryptoKey][google.cloud.kms.v1.CryptoKey] you + attempt to import into. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [ImportJob][google.cloud.kms.v1.ImportJob] was created. + generate_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this + [ImportJob][google.cloud.kms.v1.ImportJob]'s key material + was generated. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time at which this + [ImportJob][google.cloud.kms.v1.ImportJob] is scheduled for + expiration and can no longer be used to import key material. + expire_event_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time this + [ImportJob][google.cloud.kms.v1.ImportJob] expired. Only + present if [state][google.cloud.kms.v1.ImportJob.state] is + [EXPIRED][google.cloud.kms.v1.ImportJob.ImportJobState.EXPIRED]. + state (google.cloud.kms_v1.types.ImportJob.ImportJobState): + Output only. The current state of the + [ImportJob][google.cloud.kms.v1.ImportJob], indicating if it + can be used. + public_key (google.cloud.kms_v1.types.ImportJob.WrappingPublicKey): + Output only. The public key with which to wrap key material + prior to import. Only returned if + [state][google.cloud.kms.v1.ImportJob.state] is + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE]. + attestation (google.cloud.kms_v1.types.KeyOperationAttestation): + Output only. Statement that was generated and signed by the + key creator (for example, an HSM) at key creation time. Use + this statement to verify attributes of the key as stored on + the HSM, independently of Google. Only present if the chosen + [ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod] + is one with a protection level of + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM]. + """ + class ImportMethod(proto.Enum): + r"""[ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod] describes + the key wrapping method chosen for this + [ImportJob][google.cloud.kms.v1.ImportJob]. + + Values: + IMPORT_METHOD_UNSPECIFIED (0): + Not specified. + RSA_OAEP_3072_SHA1_AES_256 (1): + This ImportMethod represents the CKM_RSA_AES_KEY_WRAP key + wrapping scheme defined in the PKCS #11 standard. In + summary, this involves wrapping the raw key with an + ephemeral AES key, and wrapping the ephemeral AES key with a + 3072 bit RSA key. For more details, see `RSA AES key wrap + mechanism `__. + RSA_OAEP_4096_SHA1_AES_256 (2): + This ImportMethod represents the CKM_RSA_AES_KEY_WRAP key + wrapping scheme defined in the PKCS #11 standard. In + summary, this involves wrapping the raw key with an + ephemeral AES key, and wrapping the ephemeral AES key with a + 4096 bit RSA key. For more details, see `RSA AES key wrap + mechanism `__. + RSA_OAEP_3072_SHA256_AES_256 (3): + This ImportMethod represents the CKM_RSA_AES_KEY_WRAP key + wrapping scheme defined in the PKCS #11 standard. In + summary, this involves wrapping the raw key with an + ephemeral AES key, and wrapping the ephemeral AES key with a + 3072 bit RSA key. For more details, see `RSA AES key wrap + mechanism `__. + RSA_OAEP_4096_SHA256_AES_256 (4): + This ImportMethod represents the CKM_RSA_AES_KEY_WRAP key + wrapping scheme defined in the PKCS #11 standard. In + summary, this involves wrapping the raw key with an + ephemeral AES key, and wrapping the ephemeral AES key with a + 4096 bit RSA key. For more details, see `RSA AES key wrap + mechanism `__. + RSA_OAEP_3072_SHA256 (5): + This ImportMethod represents RSAES-OAEP with + a 3072 bit RSA key. The key material to be + imported is wrapped directly with the RSA key. + Due to technical limitations of RSA wrapping, + this method cannot be used to wrap RSA keys for + import. + RSA_OAEP_4096_SHA256 (6): + This ImportMethod represents RSAES-OAEP with + a 4096 bit RSA key. The key material to be + imported is wrapped directly with the RSA key. + Due to technical limitations of RSA wrapping, + this method cannot be used to wrap RSA keys for + import. + """ + IMPORT_METHOD_UNSPECIFIED = 0 + RSA_OAEP_3072_SHA1_AES_256 = 1 + RSA_OAEP_4096_SHA1_AES_256 = 2 + RSA_OAEP_3072_SHA256_AES_256 = 3 + RSA_OAEP_4096_SHA256_AES_256 = 4 + RSA_OAEP_3072_SHA256 = 5 + RSA_OAEP_4096_SHA256 = 6 + + class ImportJobState(proto.Enum): + r"""The state of the [ImportJob][google.cloud.kms.v1.ImportJob], + indicating if it can be used. + + Values: + IMPORT_JOB_STATE_UNSPECIFIED (0): + Not specified. + PENDING_GENERATION (1): + The wrapping key for this job is still being generated. It + may not be used. Cloud KMS will automatically mark this job + as + [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] + as soon as the wrapping key is generated. + ACTIVE (2): + This job may be used in + [CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey] + and + [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] + requests. + EXPIRED (3): + This job can no longer be used and may not + leave this state once entered. + """ + IMPORT_JOB_STATE_UNSPECIFIED = 0 + PENDING_GENERATION = 1 + ACTIVE = 2 + EXPIRED = 3 + + class WrappingPublicKey(proto.Message): + r"""The public key component of the wrapping key. For details of the + type of key this public key corresponds to, see the + [ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod]. + + Attributes: + pem (str): + The public key, encoded in PEM format. For more information, + see the `RFC 7468 `__ + sections for `General + Considerations `__ + and [Textual Encoding of Subject Public Key Info] + (https://tools.ietf.org/html/rfc7468#section-13). + """ + + pem: str = proto.Field( + proto.STRING, + number=1, + ) + + name: str = proto.Field( + proto.STRING, + number=1, + ) + import_method: ImportMethod = proto.Field( + proto.ENUM, + number=2, + enum=ImportMethod, + ) + protection_level: 'ProtectionLevel' = proto.Field( + proto.ENUM, + number=9, + enum='ProtectionLevel', + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + generate_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + expire_event_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + state: ImportJobState = proto.Field( + proto.ENUM, + number=6, + enum=ImportJobState, + ) + public_key: WrappingPublicKey = proto.Field( + proto.MESSAGE, + number=7, + message=WrappingPublicKey, + ) + attestation: 'KeyOperationAttestation' = proto.Field( + proto.MESSAGE, + number=8, + message='KeyOperationAttestation', + ) + + +class ExternalProtectionLevelOptions(proto.Message): + r"""ExternalProtectionLevelOptions stores a group of additional fields + for configuring a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] that are + specific to the + [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] protection + level and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + protection levels. + + Attributes: + external_key_uri (str): + The URI for an external resource that this + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents. + ekm_connection_key_path (str): + The path to the external key material on the EKM when using + [EkmConnection][google.cloud.kms.v1.EkmConnection] e.g., + "v0/my/key". Set this field instead of external_key_uri when + using an [EkmConnection][google.cloud.kms.v1.EkmConnection]. + """ + + external_key_uri: str = proto.Field( + proto.STRING, + number=1, + ) + ekm_connection_key_path: str = proto.Field( + proto.STRING, + number=2, + ) + + +class KeyAccessJustificationsPolicy(proto.Message): + r"""A + [KeyAccessJustificationsPolicy][google.cloud.kms.v1.KeyAccessJustificationsPolicy] + specifies zero or more allowed + [AccessReason][google.cloud.kms.v1.AccessReason] values for encrypt, + decrypt, and sign operations on a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + Attributes: + allowed_access_reasons (MutableSequence[google.cloud.kms_v1.types.AccessReason]): + The list of allowed reasons for access to a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. Zero allowed + access reasons means all encrypt, decrypt, and sign + operations for the + [CryptoKey][google.cloud.kms.v1.CryptoKey] associated with + this policy will fail. + """ + + allowed_access_reasons: MutableSequence['AccessReason'] = proto.RepeatedField( + proto.ENUM, + number=1, + enum='AccessReason', + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/service.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/service.py new file mode 100644 index 000000000000..d6e464df2ab9 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/service.py @@ -0,0 +1,2528 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +from google.cloud.kms_v1.types import resources +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore + + +__protobuf__ = proto.module( + package='google.cloud.kms.v1', + manifest={ + 'ListKeyRingsRequest', + 'ListCryptoKeysRequest', + 'ListCryptoKeyVersionsRequest', + 'ListImportJobsRequest', + 'ListKeyRingsResponse', + 'ListCryptoKeysResponse', + 'ListCryptoKeyVersionsResponse', + 'ListImportJobsResponse', + 'GetKeyRingRequest', + 'GetCryptoKeyRequest', + 'GetCryptoKeyVersionRequest', + 'GetPublicKeyRequest', + 'GetImportJobRequest', + 'CreateKeyRingRequest', + 'CreateCryptoKeyRequest', + 'CreateCryptoKeyVersionRequest', + 'ImportCryptoKeyVersionRequest', + 'CreateImportJobRequest', + 'UpdateCryptoKeyRequest', + 'UpdateCryptoKeyVersionRequest', + 'UpdateCryptoKeyPrimaryVersionRequest', + 'DestroyCryptoKeyVersionRequest', + 'RestoreCryptoKeyVersionRequest', + 'EncryptRequest', + 'DecryptRequest', + 'RawEncryptRequest', + 'RawDecryptRequest', + 'AsymmetricSignRequest', + 'AsymmetricDecryptRequest', + 'MacSignRequest', + 'MacVerifyRequest', + 'GenerateRandomBytesRequest', + 'EncryptResponse', + 'DecryptResponse', + 'RawEncryptResponse', + 'RawDecryptResponse', + 'AsymmetricSignResponse', + 'AsymmetricDecryptResponse', + 'MacSignResponse', + 'MacVerifyResponse', + 'GenerateRandomBytesResponse', + 'Digest', + 'LocationMetadata', + }, +) + + +class ListKeyRingsRequest(proto.Message): + r"""Request message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the [KeyRings][google.cloud.kms.v1.KeyRing], in the format + ``projects/*/locations/*``. + page_size (int): + Optional. Optional limit on the number of + [KeyRings][google.cloud.kms.v1.KeyRing] to include in the + response. Further [KeyRings][google.cloud.kms.v1.KeyRing] + can subsequently be obtained by including the + [ListKeyRingsResponse.next_page_token][google.cloud.kms.v1.ListKeyRingsResponse.next_page_token] + in a subsequent request. If unspecified, the server will + pick an appropriate default. + page_token (str): + Optional. Optional pagination token, returned earlier via + [ListKeyRingsResponse.next_page_token][google.cloud.kms.v1.ListKeyRingsResponse.next_page_token]. + filter (str): + Optional. Only include resources that match the filter in + the response. For more information, see `Sorting and + filtering list + results `__. + order_by (str): + Optional. Specify how the results should be sorted. If not + specified, the results will be sorted in the default order. + For more information, see `Sorting and filtering list + results `__. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListCryptoKeysRequest(proto.Message): + r"""Request message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + Attributes: + parent (str): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + page_size (int): + Optional. Optional limit on the number of + [CryptoKeys][google.cloud.kms.v1.CryptoKey] to include in + the response. Further + [CryptoKeys][google.cloud.kms.v1.CryptoKey] can subsequently + be obtained by including the + [ListCryptoKeysResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token] + in a subsequent request. If unspecified, the server will + pick an appropriate default. + page_token (str): + Optional. Optional pagination token, returned earlier via + [ListCryptoKeysResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token]. + version_view (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionView): + The fields of the primary version to include + in the response. + filter (str): + Optional. Only include resources that match the filter in + the response. For more information, see `Sorting and + filtering list + results `__. + order_by (str): + Optional. Specify how the results should be sorted. If not + specified, the results will be sorted in the default order. + For more information, see `Sorting and filtering list + results `__. + """ + + 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, + ) + version_view: resources.CryptoKeyVersion.CryptoKeyVersionView = proto.Field( + proto.ENUM, + number=4, + enum=resources.CryptoKeyVersion.CryptoKeyVersionView, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + order_by: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ListCryptoKeyVersionsRequest(proto.Message): + r"""Request message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + + Attributes: + parent (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in the + format ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. + page_size (int): + Optional. Optional limit on the number of + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] to + include in the response. Further + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + can subsequently be obtained by including the + [ListCryptoKeyVersionsResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token] + in a subsequent request. If unspecified, the server will + pick an appropriate default. + page_token (str): + Optional. Optional pagination token, returned earlier via + [ListCryptoKeyVersionsResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token]. + view (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionView): + The fields to include in the response. + filter (str): + Optional. Only include resources that match the filter in + the response. For more information, see `Sorting and + filtering list + results `__. + order_by (str): + Optional. Specify how the results should be sorted. If not + specified, the results will be sorted in the default order. + For more information, see `Sorting and filtering list + results `__. + """ + + 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, + ) + view: resources.CryptoKeyVersion.CryptoKeyVersionView = proto.Field( + proto.ENUM, + number=4, + enum=resources.CryptoKeyVersion.CryptoKeyVersionView, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + order_by: str = proto.Field( + proto.STRING, + number=6, + ) + + +class ListImportJobsRequest(proto.Message): + r"""Request message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + + Attributes: + parent (str): + Required. The resource name of the + [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the + format ``projects/*/locations/*/keyRings/*``. + page_size (int): + Optional. Optional limit on the number of + [ImportJobs][google.cloud.kms.v1.ImportJob] to include in + the response. Further + [ImportJobs][google.cloud.kms.v1.ImportJob] can subsequently + be obtained by including the + [ListImportJobsResponse.next_page_token][google.cloud.kms.v1.ListImportJobsResponse.next_page_token] + in a subsequent request. If unspecified, the server will + pick an appropriate default. + page_token (str): + Optional. Optional pagination token, returned earlier via + [ListImportJobsResponse.next_page_token][google.cloud.kms.v1.ListImportJobsResponse.next_page_token]. + filter (str): + Optional. Only include resources that match the filter in + the response. For more information, see `Sorting and + filtering list + results `__. + order_by (str): + Optional. Specify how the results should be sorted. If not + specified, the results will be sorted in the default order. + For more information, see `Sorting and filtering list + results `__. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListKeyRingsResponse(proto.Message): + r"""Response message for + [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. + + Attributes: + key_rings (MutableSequence[google.cloud.kms_v1.types.KeyRing]): + The list of [KeyRings][google.cloud.kms.v1.KeyRing]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListKeyRingsRequest.page_token][google.cloud.kms.v1.ListKeyRingsRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of [KeyRings][google.cloud.kms.v1.KeyRing] + that matched the query. + """ + + @property + def raw_page(self): + return self + + key_rings: MutableSequence[resources.KeyRing] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.KeyRing, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListCryptoKeysResponse(proto.Message): + r"""Response message for + [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. + + Attributes: + crypto_keys (MutableSequence[google.cloud.kms_v1.types.CryptoKey]): + The list of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListCryptoKeysRequest.page_token][google.cloud.kms.v1.ListCryptoKeysRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of + [CryptoKeys][google.cloud.kms.v1.CryptoKey] that matched the + query. + """ + + @property + def raw_page(self): + return self + + crypto_keys: MutableSequence[resources.CryptoKey] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.CryptoKey, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListCryptoKeyVersionsResponse(proto.Message): + r"""Response message for + [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. + + Attributes: + crypto_key_versions (MutableSequence[google.cloud.kms_v1.types.CryptoKeyVersion]): + The list of + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListCryptoKeyVersionsRequest.page_token][google.cloud.kms.v1.ListCryptoKeyVersionsRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + that matched the query. + """ + + @property + def raw_page(self): + return self + + crypto_key_versions: MutableSequence[resources.CryptoKeyVersion] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.CryptoKeyVersion, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class ListImportJobsResponse(proto.Message): + r"""Response message for + [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. + + Attributes: + import_jobs (MutableSequence[google.cloud.kms_v1.types.ImportJob]): + The list of [ImportJobs][google.cloud.kms.v1.ImportJob]. + next_page_token (str): + A token to retrieve next page of results. Pass this value in + [ListImportJobsRequest.page_token][google.cloud.kms.v1.ListImportJobsRequest.page_token] + to retrieve the next page of results. + total_size (int): + The total number of + [ImportJobs][google.cloud.kms.v1.ImportJob] that matched the + query. + """ + + @property + def raw_page(self): + return self + + import_jobs: MutableSequence[resources.ImportJob] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.ImportJob, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + total_size: int = proto.Field( + proto.INT32, + number=3, + ) + + +class GetKeyRingRequest(proto.Message): + r"""Request message for + [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] of + the [KeyRing][google.cloud.kms.v1.KeyRing] to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetCryptoKeyRequest(proto.Message): + r"""Request message for + [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] of + the [CryptoKey][google.cloud.kms.v1.CryptoKey] to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. + + Attributes: + name (str): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetPublicKeyRequest(proto.Message): + r"""Request message for + [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + + Attributes: + name (str): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + public key to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetImportJobRequest(proto.Message): + r"""Request message for + [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. + + Attributes: + name (str): + Required. The [name][google.cloud.kms.v1.ImportJob.name] of + the [ImportJob][google.cloud.kms.v1.ImportJob] to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateKeyRingRequest(proto.Message): + r"""Request message for + [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. + + Attributes: + parent (str): + Required. The resource name of the location associated with + the [KeyRings][google.cloud.kms.v1.KeyRing], in the format + ``projects/*/locations/*``. + key_ring_id (str): + Required. It must be unique within a location and match the + regular expression ``[a-zA-Z0-9_-]{1,63}`` + key_ring (google.cloud.kms_v1.types.KeyRing): + Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with + initial field values. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + key_ring_id: str = proto.Field( + proto.STRING, + number=2, + ) + key_ring: resources.KeyRing = proto.Field( + proto.MESSAGE, + number=3, + message=resources.KeyRing, + ) + + +class CreateCryptoKeyRequest(proto.Message): + r"""Request message for + [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. + + Attributes: + parent (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] of + the KeyRing associated with the + [CryptoKeys][google.cloud.kms.v1.CryptoKey]. + crypto_key_id (str): + Required. It must be unique within a KeyRing and match the + regular expression ``[a-zA-Z0-9_-]{1,63}`` + crypto_key (google.cloud.kms_v1.types.CryptoKey): + Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] with + initial field values. + skip_initial_version_creation (bool): + If set to true, the request will create a + [CryptoKey][google.cloud.kms.v1.CryptoKey] without any + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + You must manually call + [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] + or + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion] + before you can use this + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + crypto_key_id: str = proto.Field( + proto.STRING, + number=2, + ) + crypto_key: resources.CryptoKey = proto.Field( + proto.MESSAGE, + number=3, + message=resources.CryptoKey, + ) + skip_initial_version_creation: bool = proto.Field( + proto.BOOL, + number=5, + ) + + +class CreateCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. + + Attributes: + parent (str): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] of + the [CryptoKey][google.cloud.kms.v1.CryptoKey] associated + with the + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): + Required. A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with initial field values. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + crypto_key_version: resources.CryptoKeyVersion = proto.Field( + proto.MESSAGE, + number=2, + message=resources.CryptoKeyVersion, + ) + + +class ImportCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] of + the [CryptoKey][google.cloud.kms.v1.CryptoKey] to be + imported into. + + The create permission is only required on this key when + creating a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. + crypto_key_version (str): + Optional. The optional + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of an + existing + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + target for an import operation. If this field is not + present, a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + containing the supplied key material is created. + + If this field is present, the supplied key material is + imported into the existing + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. To + import into an existing + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], + the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + must be a child of + [ImportCryptoKeyVersionRequest.parent][google.cloud.kms.v1.ImportCryptoKeyVersionRequest.parent], + have been previously created via [ImportCryptoKeyVersion][], + and be in + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED] + or + [IMPORT_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.IMPORT_FAILED] + state. The key material and algorithm must match the + previous + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + exactly if the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] has + ever contained key material. + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + Required. The + [algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] + of the key being imported. This does not need to match the + [version_template][google.cloud.kms.v1.CryptoKey.version_template] + of the [CryptoKey][google.cloud.kms.v1.CryptoKey] this + version imports into. + import_job (str): + Required. The [name][google.cloud.kms.v1.ImportJob.name] of + the [ImportJob][google.cloud.kms.v1.ImportJob] that was used + to wrap this key material. + wrapped_key (bytes): + Optional. The wrapped key material to import. + + Before wrapping, key material must be formatted. If + importing symmetric key material, the expected key material + format is plain bytes. If importing asymmetric key material, + the expected key material format is PKCS#8-encoded DER (the + PrivateKeyInfo structure from RFC 5208). + + When wrapping with import methods + ([RSA_OAEP_3072_SHA1_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256] + or + [RSA_OAEP_4096_SHA1_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA1_AES_256] + or + [RSA_OAEP_3072_SHA256_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA256_AES_256] + or + [RSA_OAEP_4096_SHA256_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA256_AES_256]), + + this field must contain the concatenation of: + + .. raw:: html + +
    +
  1. An ephemeral AES-256 wrapping key wrapped with the + [public_key][google.cloud.kms.v1.ImportJob.public_key] using + RSAES-OAEP with SHA-1/SHA-256, MGF1 with SHA-1/SHA-256, and an empty + label. +
  2. +
  3. The formatted key to be imported, wrapped with the ephemeral AES-256 + key using AES-KWP (RFC 5649). +
  4. +
+ + This format is the same as the format produced by PKCS#11 + mechanism CKM_RSA_AES_KEY_WRAP. + + When wrapping with import methods + ([RSA_OAEP_3072_SHA256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA256] + or + [RSA_OAEP_4096_SHA256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA256]), + + this field must contain the formatted key to be imported, + wrapped with the + [public_key][google.cloud.kms.v1.ImportJob.public_key] using + RSAES-OAEP with SHA-256, MGF1 with SHA-256, and an empty + label. + rsa_aes_wrapped_key (bytes): + Optional. This field has the same meaning as + [wrapped_key][google.cloud.kms.v1.ImportCryptoKeyVersionRequest.wrapped_key]. + Prefer to use that field in new work. Either that field or + this field (but not both) must be specified. + + This field is a member of `oneof`_ ``wrapped_key_material``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + crypto_key_version: str = proto.Field( + proto.STRING, + number=6, + ) + algorithm: resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm = proto.Field( + proto.ENUM, + number=2, + enum=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm, + ) + import_job: str = proto.Field( + proto.STRING, + number=4, + ) + wrapped_key: bytes = proto.Field( + proto.BYTES, + number=8, + ) + rsa_aes_wrapped_key: bytes = proto.Field( + proto.BYTES, + number=5, + oneof='wrapped_key_material', + ) + + +class CreateImportJobRequest(proto.Message): + r"""Request message for + [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. + + Attributes: + parent (str): + Required. The [name][google.cloud.kms.v1.KeyRing.name] of + the [KeyRing][google.cloud.kms.v1.KeyRing] associated with + the [ImportJobs][google.cloud.kms.v1.ImportJob]. + import_job_id (str): + Required. It must be unique within a KeyRing and match the + regular expression ``[a-zA-Z0-9_-]{1,63}`` + import_job (google.cloud.kms_v1.types.ImportJob): + Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with + initial field values. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + import_job_id: str = proto.Field( + proto.STRING, + number=2, + ) + import_job: resources.ImportJob = proto.Field( + proto.MESSAGE, + number=3, + message=resources.ImportJob, + ) + + +class UpdateCryptoKeyRequest(proto.Message): + r"""Request message for + [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. + + Attributes: + crypto_key (google.cloud.kms_v1.types.CryptoKey): + Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] with + updated values. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + crypto_key: resources.CryptoKey = proto.Field( + proto.MESSAGE, + number=1, + message=resources.CryptoKey, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. + + Attributes: + crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): + Required. + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + with updated values. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Required. List of fields to be updated in + this request. + """ + + crypto_key_version: resources.CryptoKeyVersion = proto.Field( + proto.MESSAGE, + number=1, + message=resources.CryptoKeyVersion, + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + + +class UpdateCryptoKeyPrimaryVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. + crypto_key_version_id (str): + Required. The id of the child + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use as primary. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + crypto_key_version_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DestroyCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + destroy. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class RestoreCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + restore. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class EncryptRequest(proto.Message): + r"""Request message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] or + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for encryption. + + If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is + specified, the server will use its [primary + version][google.cloud.kms.v1.CryptoKey.primary]. + plaintext (bytes): + Required. The data to encrypt. Must be no larger than 64KiB. + + The maximum size depends on the key version's + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. + For + [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE], + [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL], + and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + keys, the plaintext must be no larger than 64KiB. For + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the + combined length of the plaintext and + additional_authenticated_data fields must be no larger than + 8KiB. + additional_authenticated_data (bytes): + Optional. Optional data that, if specified, must also be + provided during decryption through + [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]. + + The maximum size depends on the key version's + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. + For + [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE], + [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL], + and + [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] + keys the AAD must be no larger than 64KiB. For + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the + combined length of the plaintext and + additional_authenticated_data fields must be no larger than + 8KiB. + plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]) + is equal to + [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]) + is equal to + [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + plaintext: bytes = proto.Field( + proto.BYTES, + number=2, + ) + additional_authenticated_data: bytes = proto.Field( + proto.BYTES, + number=3, + ) + plaintext_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=7, + message=wrappers_pb2.Int64Value, + ) + additional_authenticated_data_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=8, + message=wrappers_pb2.Int64Value, + ) + + +class DecryptRequest(proto.Message): + r"""Request message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for + decryption. The server will choose the appropriate version. + ciphertext (bytes): + Required. The encrypted data originally returned in + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. + additional_authenticated_data (bytes): + Optional. Optional data that must match the data originally + supplied in + [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. + ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]) + is equal to + [DecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.DecryptRequest.ciphertext_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]) + is equal to + [DecryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ciphertext: bytes = proto.Field( + proto.BYTES, + number=2, + ) + additional_authenticated_data: bytes = proto.Field( + proto.BYTES, + number=3, + ) + ciphertext_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.Int64Value, + ) + additional_authenticated_data_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.Int64Value, + ) + + +class RawEncryptRequest(proto.Message): + r"""Request message for + [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for encryption. + plaintext (bytes): + Required. The data to encrypt. Must be no larger than 64KiB. + + The maximum size depends on the key version's + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. + For [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] + keys, the plaintext must be no larger than 64KiB. For + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the + combined length of the plaintext and + additional_authenticated_data fields must be no larger than + 8KiB. + additional_authenticated_data (bytes): + Optional. Optional data that, if specified, must also be + provided during decryption through + [RawDecryptRequest.additional_authenticated_data][google.cloud.kms.v1.RawDecryptRequest.additional_authenticated_data]. + + This field may only be used in conjunction with an + [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm] + that accepts additional authenticated data (for example, + AES-GCM). + + The maximum size depends on the key version's + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. + For [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] + keys, the plaintext must be no larger than 64KiB. For + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the + combined length of the plaintext and + additional_authenticated_data fields must be no larger than + 8KiB. + plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [RawEncryptRequest.plaintext][google.cloud.kms.v1.RawEncryptRequest.plaintext]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received plaintext using + this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C(plaintext) is equal to plaintext_crc32c, and if so, + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [RawEncryptRequest.additional_authenticated_data][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + additional_authenticated_data using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C(additional_authenticated_data) is equal to + additional_authenticated_data_crc32c, and if so, perform a + limited number of retries. A persistent mismatch may + indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + initialization_vector (bytes): + Optional. A customer-supplied initialization vector that + will be used for encryption. If it is not provided for + AES-CBC and AES-CTR, one will be generated. It will be + returned in + [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector]. + initialization_vector_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [RawEncryptRequest.initialization_vector][google.cloud.kms.v1.RawEncryptRequest.initialization_vector]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + initialization_vector using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C(initialization_vector) is equal to + initialization_vector_crc32c, and if so, perform a limited + number of retries. A persistent mismatch may indicate an + issue in your computation of the CRC32C checksum. Note: This + field is defined as int64 for reasons of compatibility + across different languages. However, it is a non-negative + integer, which will never exceed 2^32-1, and can be safely + downconverted to uint32 in languages that support this type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + plaintext: bytes = proto.Field( + proto.BYTES, + number=2, + ) + additional_authenticated_data: bytes = proto.Field( + proto.BYTES, + number=3, + ) + plaintext_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=4, + message=wrappers_pb2.Int64Value, + ) + additional_authenticated_data_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.Int64Value, + ) + initialization_vector: bytes = proto.Field( + proto.BYTES, + number=6, + ) + initialization_vector_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=7, + message=wrappers_pb2.Int64Value, + ) + + +class RawDecryptRequest(proto.Message): + r"""Request message for + [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for decryption. + ciphertext (bytes): + Required. The encrypted data originally returned in + [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext]. + additional_authenticated_data (bytes): + Optional. Optional data that must match the data originally + supplied in + [RawEncryptRequest.additional_authenticated_data][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data]. + initialization_vector (bytes): + Required. The initialization vector (IV) used during + encryption, which must match the data originally provided in + [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector]. + tag_length (int): + The length of the authentication tag that is + appended to the end of the ciphertext. If + unspecified (0), the default value for the key's + algorithm will be used (for AES-GCM, the default + value is 16). + ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [RawDecryptRequest.ciphertext][google.cloud.kms.v1.RawDecryptRequest.ciphertext]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received ciphertext using + this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C(ciphertext) is equal to ciphertext_crc32c, and if so, + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [RawDecryptRequest.additional_authenticated_data][google.cloud.kms.v1.RawDecryptRequest.additional_authenticated_data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + additional_authenticated_data using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C(additional_authenticated_data) is equal to + additional_authenticated_data_crc32c, and if so, perform a + limited number of retries. A persistent mismatch may + indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + initialization_vector_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [RawDecryptRequest.initialization_vector][google.cloud.kms.v1.RawDecryptRequest.initialization_vector]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + initialization_vector using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C(initialization_vector) is equal to + initialization_vector_crc32c, and if so, perform a limited + number of retries. A persistent mismatch may indicate an + issue in your computation of the CRC32C checksum. Note: This + field is defined as int64 for reasons of compatibility + across different languages. However, it is a non-negative + integer, which will never exceed 2^32-1, and can be safely + downconverted to uint32 in languages that support this type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ciphertext: bytes = proto.Field( + proto.BYTES, + number=2, + ) + additional_authenticated_data: bytes = proto.Field( + proto.BYTES, + number=3, + ) + initialization_vector: bytes = proto.Field( + proto.BYTES, + number=4, + ) + tag_length: int = proto.Field( + proto.INT32, + number=5, + ) + ciphertext_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=6, + message=wrappers_pb2.Int64Value, + ) + additional_authenticated_data_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=7, + message=wrappers_pb2.Int64Value, + ) + initialization_vector_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=8, + message=wrappers_pb2.Int64Value, + ) + + +class AsymmetricSignRequest(proto.Message): + r"""Request message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for signing. + digest (google.cloud.kms_v1.types.Digest): + Optional. The digest of the data to sign. The digest must be + produced with the same digest algorithm as specified by the + key version's + [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. + + This field may not be supplied if + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + is supplied. + digest_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]) + is equal to + [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + data (bytes): + Optional. The data to sign. It can't be supplied if + [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest] + is supplied. + data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]) + is equal to + [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + digest: 'Digest' = proto.Field( + proto.MESSAGE, + number=3, + message='Digest', + ) + digest_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=4, + message=wrappers_pb2.Int64Value, + ) + data: bytes = proto.Field( + proto.BYTES, + number=6, + ) + data_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=7, + message=wrappers_pb2.Int64Value, + ) + + +class AsymmetricDecryptRequest(proto.Message): + r"""Request message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for decryption. + ciphertext (bytes): + Required. The data encrypted with the named + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s + public key using OAEP. + ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]) + is equal to + [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ciphertext: bytes = proto.Field( + proto.BYTES, + number=3, + ) + ciphertext_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=4, + message=wrappers_pb2.Int64Value, + ) + + +class MacSignRequest(proto.Message): + r"""Request message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for signing. + data (bytes): + Required. The data to sign. The MAC tag is + computed over this data field based on the + specific algorithm. + data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data]) + is equal to + [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data: bytes = proto.Field( + proto.BYTES, + number=2, + ) + data_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int64Value, + ) + + +class MacVerifyRequest(proto.Message): + r"""Request message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + + Attributes: + name (str): + Required. The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use for verification. + data (bytes): + Required. The data used previously as a + [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] + to generate the MAC tag. + data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data]) + is equal to + [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + mac (bytes): + Required. The signature to verify. + mac_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Optional. An optional CRC32C checksum of the + [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac]. + If specified, + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will verify the integrity of the received + [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac] + using this checksum. + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + will report an error if the checksum verification fails. If + you receive a checksum error, your client should verify that + CRC32C([MacVerifyRequest.tag][]) is equal to + [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c], + and if so, perform a limited number of retries. A persistent + mismatch may indicate an issue in your computation of the + CRC32C checksum. Note: This field is defined as int64 for + reasons of compatibility across different languages. + However, it is a non-negative integer, which will never + exceed 2^32-1, and can be safely downconverted to uint32 in + languages that support this type. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + data: bytes = proto.Field( + proto.BYTES, + number=2, + ) + data_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int64Value, + ) + mac: bytes = proto.Field( + proto.BYTES, + number=4, + ) + mac_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.Int64Value, + ) + + +class GenerateRandomBytesRequest(proto.Message): + r"""Request message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + + Attributes: + location (str): + The project-specific location in which to + generate random bytes. For example, + "projects/my-project/locations/us-central1". + length_bytes (int): + The length in bytes of the amount of + randomness to retrieve. Minimum 8 bytes, + maximum 1024 bytes. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + to use when generating the random data. Currently, only + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] protection + level is supported. + """ + + location: str = proto.Field( + proto.STRING, + number=1, + ) + length_bytes: int = proto.Field( + proto.INT32, + number=2, + ) + protection_level: resources.ProtectionLevel = proto.Field( + proto.ENUM, + number=3, + enum=resources.ProtectionLevel, + ) + + +class EncryptResponse(proto.Message): + r"""Response message for + [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. + + Attributes: + name (str): + The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used in encryption. Check this field to verify that the + intended resource was used for encryption. + ciphertext (bytes): + The encrypted data. + ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. + An integrity check of + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext] + can be performed by computing the CRC32C checksum of + [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + verified_plaintext_crc32c (bool): + Integrity verification field. A flag indicating whether + [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. A + false value of this field indicates either that + [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + verified_additional_authenticated_data_crc32c (bool): + Integrity verification field. A flag indicating whether + [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [AAD][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. + A false value of this field indicates either that + [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used in encryption. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ciphertext: bytes = proto.Field( + proto.BYTES, + number=2, + ) + ciphertext_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=4, + message=wrappers_pb2.Int64Value, + ) + verified_plaintext_crc32c: bool = proto.Field( + proto.BOOL, + number=5, + ) + verified_additional_authenticated_data_crc32c: bool = proto.Field( + proto.BOOL, + number=6, + ) + protection_level: resources.ProtectionLevel = proto.Field( + proto.ENUM, + number=7, + enum=resources.ProtectionLevel, + ) + + +class DecryptResponse(proto.Message): + r"""Response message for + [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + + Attributes: + plaintext (bytes): + The decrypted data originally supplied in + [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. + plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext]. + An integrity check of + [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext] + can be performed by computing the CRC32C checksum of + [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: receiving this response message indicates + that + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + is able to successfully decrypt the + [ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]. + Note: This field is defined as int64 for reasons of + compatibility across different languages. However, it is a + non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + used_primary (bool): + Whether the Decryption was performed using + the primary key version. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used in decryption. + """ + + plaintext: bytes = proto.Field( + proto.BYTES, + number=1, + ) + plaintext_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int64Value, + ) + used_primary: bool = proto.Field( + proto.BOOL, + number=3, + ) + protection_level: resources.ProtectionLevel = proto.Field( + proto.ENUM, + number=4, + enum=resources.ProtectionLevel, + ) + + +class RawEncryptResponse(proto.Message): + r"""Response message for + [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. + + Attributes: + ciphertext (bytes): + The encrypted data. In the case of AES-GCM, the + authentication tag is the + [tag_length][google.cloud.kms.v1.RawEncryptResponse.tag_length] + bytes at the end of this field. + initialization_vector (bytes): + The initialization vector (IV) generated by the service + during encryption. This value must be stored and provided in + [RawDecryptRequest.initialization_vector][google.cloud.kms.v1.RawDecryptRequest.initialization_vector] + at decryption time. + tag_length (int): + The length of the authentication tag that is + appended to the end of the ciphertext. + ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext]. + An integrity check of ciphertext can be performed by + computing the CRC32C checksum of ciphertext and comparing + your results to this field. Discard the response in case of + non-matching checksum values, and perform a limited number + of retries. A persistent mismatch may indicate an issue in + your computation of the CRC32C checksum. Note: This field is + defined as int64 for reasons of compatibility across + different languages. However, it is a non-negative integer, + which will never exceed 2^32-1, and can be safely + downconverted to uint32 in languages that support this type. + initialization_vector_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector]. + An integrity check of initialization_vector can be performed + by computing the CRC32C checksum of initialization_vector + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + verified_plaintext_crc32c (bool): + Integrity verification field. A flag indicating whether + [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the plaintext. A + false value of this field indicates either that + [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + verified_additional_authenticated_data_crc32c (bool): + Integrity verification field. A flag indicating whether + [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of + additional_authenticated_data. A false value of this field + indicates either that // + [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + verified_initialization_vector_crc32c (bool): + Integrity verification field. A flag indicating whether + [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of + initialization_vector. A false value of this field indicates + either that + [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + name (str): + The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used in encryption. Check this field to verify that the + intended resource was used for encryption. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used in encryption. + """ + + ciphertext: bytes = proto.Field( + proto.BYTES, + number=1, + ) + initialization_vector: bytes = proto.Field( + proto.BYTES, + number=2, + ) + tag_length: int = proto.Field( + proto.INT32, + number=3, + ) + ciphertext_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=4, + message=wrappers_pb2.Int64Value, + ) + initialization_vector_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=5, + message=wrappers_pb2.Int64Value, + ) + verified_plaintext_crc32c: bool = proto.Field( + proto.BOOL, + number=6, + ) + verified_additional_authenticated_data_crc32c: bool = proto.Field( + proto.BOOL, + number=7, + ) + verified_initialization_vector_crc32c: bool = proto.Field( + proto.BOOL, + number=10, + ) + name: str = proto.Field( + proto.STRING, + number=8, + ) + protection_level: resources.ProtectionLevel = proto.Field( + proto.ENUM, + number=9, + enum=resources.ProtectionLevel, + ) + + +class RawDecryptResponse(proto.Message): + r"""Response message for + [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. + + Attributes: + plaintext (bytes): + The decrypted data. + plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [RawDecryptResponse.plaintext][google.cloud.kms.v1.RawDecryptResponse.plaintext]. + An integrity check of plaintext can be performed by + computing the CRC32C checksum of plaintext and comparing + your results to this field. Discard the response in case of + non-matching checksum values, and perform a limited number + of retries. A persistent mismatch may indicate an issue in + your computation of the CRC32C checksum. Note: receiving + this response message indicates that + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + is able to successfully decrypt the + [ciphertext][google.cloud.kms.v1.RawDecryptRequest.ciphertext]. + Note: This field is defined as int64 for reasons of + compatibility across different languages. However, it is a + non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used in decryption. + verified_ciphertext_crc32c (bool): + Integrity verification field. A flag indicating whether + [RawDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.RawDecryptRequest.ciphertext_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the ciphertext. A + false value of this field indicates either that + [RawDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.RawDecryptRequest.ciphertext_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [RawDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.RawDecryptRequest.ciphertext_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + verified_additional_authenticated_data_crc32c (bool): + Integrity verification field. A flag indicating whether + [RawDecryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawDecryptRequest.additional_authenticated_data_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of + additional_authenticated_data. A false value of this field + indicates either that // + [RawDecryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawDecryptRequest.additional_authenticated_data_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [RawDecryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawDecryptRequest.additional_authenticated_data_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + verified_initialization_vector_crc32c (bool): + Integrity verification field. A flag indicating whether + [RawDecryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawDecryptRequest.initialization_vector_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of + initialization_vector. A false value of this field indicates + either that + [RawDecryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawDecryptRequest.initialization_vector_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [RawDecryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawDecryptRequest.initialization_vector_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + """ + + plaintext: bytes = proto.Field( + proto.BYTES, + number=1, + ) + plaintext_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int64Value, + ) + protection_level: resources.ProtectionLevel = proto.Field( + proto.ENUM, + number=3, + enum=resources.ProtectionLevel, + ) + verified_ciphertext_crc32c: bool = proto.Field( + proto.BOOL, + number=4, + ) + verified_additional_authenticated_data_crc32c: bool = proto.Field( + proto.BOOL, + number=5, + ) + verified_initialization_vector_crc32c: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class AsymmetricSignResponse(proto.Message): + r"""Response message for + [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. + + Attributes: + signature (bytes): + The created signature. + signature_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature]. + An integrity check of + [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature] + can be performed by computing the CRC32C checksum of + [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + verified_digest_crc32c (bool): + Integrity verification field. A flag indicating whether + [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. + A false value of this field indicates either that + [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + name (str): + The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for signing. Check this field to verify that the + intended resource was used for signing. + verified_data_crc32c (bool): + Integrity verification field. A flag indicating whether + [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [data][google.cloud.kms.v1.AsymmetricSignRequest.data]. A + false value of this field indicates either that + [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for signing. + """ + + signature: bytes = proto.Field( + proto.BYTES, + number=1, + ) + signature_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int64Value, + ) + verified_digest_crc32c: bool = proto.Field( + proto.BOOL, + number=3, + ) + name: str = proto.Field( + proto.STRING, + number=4, + ) + verified_data_crc32c: bool = proto.Field( + proto.BOOL, + number=5, + ) + protection_level: resources.ProtectionLevel = proto.Field( + proto.ENUM, + number=6, + enum=resources.ProtectionLevel, + ) + + +class AsymmetricDecryptResponse(proto.Message): + r"""Response message for + [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. + + Attributes: + plaintext (bytes): + The decrypted data originally encrypted with + the matching public key. + plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext]. + An integrity check of + [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext] + can be performed by computing the CRC32C checksum of + [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + verified_ciphertext_crc32c (bool): + Integrity verification field. A flag indicating whether + [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]. + A false value of this field indicates either that + [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used in decryption. + """ + + plaintext: bytes = proto.Field( + proto.BYTES, + number=1, + ) + plaintext_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int64Value, + ) + verified_ciphertext_crc32c: bool = proto.Field( + proto.BOOL, + number=3, + ) + protection_level: resources.ProtectionLevel = proto.Field( + proto.ENUM, + number=4, + enum=resources.ProtectionLevel, + ) + + +class MacSignResponse(proto.Message): + r"""Response message for + [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. + + Attributes: + name (str): + The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for signing. Check this field to verify that the + intended resource was used for signing. + mac (bytes): + The created signature. + mac_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac]. + An integrity check of + [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac] + can be performed by computing the CRC32C checksum of + [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + verified_data_crc32c (bool): + Integrity verification field. A flag indicating whether + [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [data][google.cloud.kms.v1.MacSignRequest.data]. A false + value of this field indicates either that + [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for signing. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + mac: bytes = proto.Field( + proto.BYTES, + number=2, + ) + mac_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int64Value, + ) + verified_data_crc32c: bool = proto.Field( + proto.BOOL, + number=4, + ) + protection_level: resources.ProtectionLevel = proto.Field( + proto.ENUM, + number=5, + enum=resources.ProtectionLevel, + ) + + +class MacVerifyResponse(proto.Message): + r"""Response message for + [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. + + Attributes: + name (str): + The resource name of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for verification. Check this field to verify that the + intended resource was used for verification. + success (bool): + This field indicates whether or not the verification + operation for + [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac] + over + [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data] + was successful. + verified_data_crc32c (bool): + Integrity verification field. A flag indicating whether + [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [data][google.cloud.kms.v1.MacVerifyRequest.data]. A false + value of this field indicates either that + [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + verified_mac_crc32c (bool): + Integrity verification field. A flag indicating whether + [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] + was received by + [KeyManagementService][google.cloud.kms.v1.KeyManagementService] + and used for the integrity verification of the + [data][google.cloud.kms.v1.MacVerifyRequest.mac]. A false + value of this field indicates either that + [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] + was left unset or that it was not delivered to + [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. + If you've set + [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] + but this field is still false, discard the response and + perform a limited number of retries. + verified_success_integrity (bool): + Integrity verification field. This value is used for the + integrity verification of [MacVerifyResponse.success]. If + the value of this field contradicts the value of + [MacVerifyResponse.success], discard the response and + perform a limited number of retries. + protection_level (google.cloud.kms_v1.types.ProtectionLevel): + The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] + of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + used for verification. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + success: bool = proto.Field( + proto.BOOL, + number=2, + ) + verified_data_crc32c: bool = proto.Field( + proto.BOOL, + number=3, + ) + verified_mac_crc32c: bool = proto.Field( + proto.BOOL, + number=4, + ) + verified_success_integrity: bool = proto.Field( + proto.BOOL, + number=5, + ) + protection_level: resources.ProtectionLevel = proto.Field( + proto.ENUM, + number=6, + enum=resources.ProtectionLevel, + ) + + +class GenerateRandomBytesResponse(proto.Message): + r"""Response message for + [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. + + Attributes: + data (bytes): + The generated data. + data_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data]. + An integrity check of + [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data] + can be performed by computing the CRC32C checksum of + [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + """ + + data: bytes = proto.Field( + proto.BYTES, + number=1, + ) + data_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=3, + message=wrappers_pb2.Int64Value, + ) + + +class Digest(proto.Message): + r"""A [Digest][google.cloud.kms.v1.Digest] holds a cryptographic message + digest. + + 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: + sha256 (bytes): + A message digest produced with the SHA-256 + algorithm. + + This field is a member of `oneof`_ ``digest``. + sha384 (bytes): + A message digest produced with the SHA-384 + algorithm. + + This field is a member of `oneof`_ ``digest``. + sha512 (bytes): + A message digest produced with the SHA-512 + algorithm. + + This field is a member of `oneof`_ ``digest``. + """ + + sha256: bytes = proto.Field( + proto.BYTES, + number=1, + oneof='digest', + ) + sha384: bytes = proto.Field( + proto.BYTES, + number=2, + oneof='digest', + ) + sha512: bytes = proto.Field( + proto.BYTES, + number=3, + oneof='digest', + ) + + +class LocationMetadata(proto.Message): + r"""Cloud KMS metadata for the given + [google.cloud.location.Location][google.cloud.location.Location]. + + Attributes: + hsm_available (bool): + Indicates whether + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] + [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] can be + created in this location. + ekm_available (bool): + Indicates whether + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with + [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] + [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] can + be created in this location. + """ + + hsm_available: bool = proto.Field( + proto.BOOL, + number=1, + ) + ekm_available: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-kms/v1/mypy.ini b/owl-bot-staging/google-cloud-kms/v1/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/owl-bot-staging/google-cloud-kms/v1/noxfile.py b/owl-bot-staging/google-cloud-kms/v1/noxfile.py new file mode 100644 index 000000000000..c69e2b65d2fe --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/noxfile.py @@ -0,0 +1,280 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +import pathlib +import re +import shutil +import subprocess +import sys + + +import nox # type: ignore + +ALL_PYTHON = [ + "3.7", + "3.8", + "3.9", + "3.10", + "3.11", + "3.12", + "3.13", +] + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" +PACKAGE_NAME = 'google-cloud-kms' + +BLACK_VERSION = "black==22.3.0" +BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] +DEFAULT_PYTHON_VERSION = "3.13" + +nox.sessions = [ + "unit", + "cover", + "mypy", + "check_lower_bounds" + # exclude update_lower_bounds from default + "docs", + "blacken", + "lint", + "prerelease_deps", +] + +@nox.session(python=ALL_PYTHON) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def unit(session, protobuf_implementation): + """Run the unit test suite.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") + + # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. + # The 'cpp' implementation requires Protobuf<4. + if protobuf_implementation == "cpp": + session.install("protobuf<4") + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/kms_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + +@nox.session(python=ALL_PYTHON[-1]) +@nox.parametrize( + "protobuf_implementation", + [ "python", "upb", "cpp" ], +) +def prerelease_deps(session, protobuf_implementation): + """Run the unit test suite against pre-release versions of dependencies.""" + + if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): + session.skip("cpp implementation is not supported in python 3.11+") + + # Install test environment dependencies + session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') + + # Install the package without dependencies + session.install('-e', '.', '--no-deps') + + # We test the minimum dependency versions using the minimum Python + # version so the lowest python runtime that we test has a corresponding constraints + # file, located at `testing/constraints--.txt`, which contains all of the + # dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{ALL_PYTHON[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "googleapis-common-protos", + "google-api-core", + "google-auth", + # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 + "grpcio!=1.67.0rc1", + "grpcio-status", + "protobuf", + "proto-plus", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + + session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run( + "python", "-c", "import proto; print(proto.__version__)" + ) + + session.run( + 'py.test', + '--quiet', + '--cov=google/cloud/kms_v1/', + '--cov=tests/', + '--cov-config=.coveragerc', + '--cov-report=term', + '--cov-report=html', + os.path.join('tests', 'unit', ''.join(session.posargs)), + env={ + "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, + }, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=ALL_PYTHON) +def mypy(session): + """Run the type checker.""" + session.install( + 'mypy', + 'types-requests', + 'types-protobuf' + ) + session.install('.') + session.run( + 'mypy', + '-p', + 'google', + ) + + +@nox.session +def update_lower_bounds(session): + """Update lower bounds in constraints.txt to match setup.py""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'update', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + + +@nox.session +def check_lower_bounds(session): + """Check lower bounds in setup.py are reflected in constraints file""" + session.install('google-cloud-testutils') + session.install('.') + + session.run( + 'lower-bound-checker', + 'check', + '--package-name', + PACKAGE_NAME, + '--constraints-file', + str(LOWER_BOUND_CONSTRAINTS_FILE), + ) + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install("sphinx==7.0.1", "alabaster", "recommonmark") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *BLACK_PATHS, + ) + session.run("flake8", "google", "tests", "samples") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *BLACK_PATHS, + ) diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py new file mode 100644 index 000000000000..ee0d04fe9e37 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutokeyConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_get_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetAutokeyConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_autokey_config(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py new file mode 100644 index 000000000000..f69beed0cc49 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetAutokeyConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_get_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminClient() + + # Initialize request argument(s) + request = kms_v1.GetAutokeyConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_autokey_config(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py new file mode 100644 index 000000000000..e1a84b2d8f16 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ShowEffectiveAutokeyConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_show_effective_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ShowEffectiveAutokeyConfigRequest( + parent="parent_value", + ) + + # Make the request + response = await client.show_effective_autokey_config(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py new file mode 100644 index 000000000000..947a97892bd3 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ShowEffectiveAutokeyConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_show_effective_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminClient() + + # Initialize request argument(s) + request = kms_v1.ShowEffectiveAutokeyConfigRequest( + parent="parent_value", + ) + + # Make the request + response = client.show_effective_autokey_config(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py new file mode 100644 index 000000000000..020948ebd222 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutokeyConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_update_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateAutokeyConfigRequest( + ) + + # Make the request + response = await client.update_autokey_config(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py new file mode 100644 index 000000000000..b4b16c13c813 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateAutokeyConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_update_autokey_config(): + # Create a client + client = kms_v1.AutokeyAdminClient() + + # Initialize request argument(s) + request = kms_v1.UpdateAutokeyConfigRequest( + ) + + # Make the request + response = client.update_autokey_config(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_async.py new file mode 100644 index 000000000000..8ce14b9513d9 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_async.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateKeyHandle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_Autokey_CreateKeyHandle_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_create_key_handle(): + # Create a client + client = kms_v1.AutokeyAsyncClient() + + # Initialize request argument(s) + key_handle = kms_v1.KeyHandle() + key_handle.resource_type_selector = "resource_type_selector_value" + + request = kms_v1.CreateKeyHandleRequest( + parent="parent_value", + key_handle=key_handle, + ) + + # Make the request + operation = client.create_key_handle(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_Autokey_CreateKeyHandle_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_sync.py new file mode 100644 index 000000000000..694507475e42 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_sync.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateKeyHandle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_Autokey_CreateKeyHandle_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_create_key_handle(): + # Create a client + client = kms_v1.AutokeyClient() + + # Initialize request argument(s) + key_handle = kms_v1.KeyHandle() + key_handle.resource_type_selector = "resource_type_selector_value" + + request = kms_v1.CreateKeyHandleRequest( + parent="parent_value", + key_handle=key_handle, + ) + + # Make the request + operation = client.create_key_handle(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_Autokey_CreateKeyHandle_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_async.py new file mode 100644 index 000000000000..3442ce5864ad --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetKeyHandle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_Autokey_GetKeyHandle_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_get_key_handle(): + # Create a client + client = kms_v1.AutokeyAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetKeyHandleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_key_handle(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_Autokey_GetKeyHandle_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_sync.py new file mode 100644 index 000000000000..08ce1a40467a --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetKeyHandle +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_Autokey_GetKeyHandle_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_get_key_handle(): + # Create a client + client = kms_v1.AutokeyClient() + + # Initialize request argument(s) + request = kms_v1.GetKeyHandleRequest( + name="name_value", + ) + + # Make the request + response = client.get_key_handle(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_Autokey_GetKeyHandle_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_async.py new file mode 100644 index 000000000000..bc76498134df --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListKeyHandles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_Autokey_ListKeyHandles_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_list_key_handles(): + # Create a client + client = kms_v1.AutokeyAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListKeyHandlesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_handles(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudkms_v1_generated_Autokey_ListKeyHandles_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_sync.py new file mode 100644 index 000000000000..6a7ef9a327e8 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListKeyHandles +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_Autokey_ListKeyHandles_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_list_key_handles(): + # Create a client + client = kms_v1.AutokeyClient() + + # Initialize request argument(s) + request = kms_v1.ListKeyHandlesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_handles(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudkms_v1_generated_Autokey_ListKeyHandles_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py new file mode 100644 index 000000000000..98bb8aa4bdc5 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEkmConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_CreateEkmConnection_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_create_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.CreateEkmConnectionRequest( + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ) + + # Make the request + response = await client.create_ekm_connection(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_CreateEkmConnection_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py new file mode 100644 index 000000000000..c17c9b6f4e13 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateEkmConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_CreateEkmConnection_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_create_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.CreateEkmConnectionRequest( + parent="parent_value", + ekm_connection_id="ekm_connection_id_value", + ) + + # Make the request + response = client.create_ekm_connection(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_CreateEkmConnection_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_async.py new file mode 100644 index 000000000000..e1004f23cd5c --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEkmConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_GetEkmConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_get_ekm_config(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetEkmConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_ekm_config(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_GetEkmConfig_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py new file mode 100644 index 000000000000..d0abf9952dc4 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEkmConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_GetEkmConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_get_ekm_config(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetEkmConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_ekm_config(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_GetEkmConfig_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py new file mode 100644 index 000000000000..0ef3b3b2362a --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEkmConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_GetEkmConnection_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_get_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetEkmConnectionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_ekm_connection(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_GetEkmConnection_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py new file mode 100644 index 000000000000..5f711e9b130b --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetEkmConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_GetEkmConnection_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_get_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetEkmConnectionRequest( + name="name_value", + ) + + # Make the request + response = client.get_ekm_connection(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_GetEkmConnection_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py new file mode 100644 index 000000000000..a7f411307441 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEkmConnections +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_ListEkmConnections_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_list_ekm_connections(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListEkmConnectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_ekm_connections(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudkms_v1_generated_EkmService_ListEkmConnections_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py new file mode 100644 index 000000000000..9455ecdf9518 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListEkmConnections +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_ListEkmConnections_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_list_ekm_connections(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.ListEkmConnectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_ekm_connections(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudkms_v1_generated_EkmService_ListEkmConnections_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_async.py new file mode 100644 index 000000000000..9403690e5be2 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEkmConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_UpdateEkmConfig_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_update_ekm_config(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateEkmConfigRequest( + ) + + # Make the request + response = await client.update_ekm_config(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_UpdateEkmConfig_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py new file mode 100644 index 000000000000..7357a475cd7e --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEkmConfig +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_UpdateEkmConfig_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_update_ekm_config(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.UpdateEkmConfigRequest( + ) + + # Make the request + response = client.update_ekm_config(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_UpdateEkmConfig_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py new file mode 100644 index 000000000000..8f61b8003f64 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEkmConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_UpdateEkmConnection_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_update_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateEkmConnectionRequest( + ) + + # Make the request + response = await client.update_ekm_connection(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_UpdateEkmConnection_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py new file mode 100644 index 000000000000..7d3637358348 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateEkmConnection +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_UpdateEkmConnection_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_update_ekm_connection(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.UpdateEkmConnectionRequest( + ) + + # Make the request + response = client.update_ekm_connection(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_UpdateEkmConnection_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py new file mode 100644 index 000000000000..fb5824c4f4ac --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for VerifyConnectivity +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_VerifyConnectivity_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_verify_connectivity(): + # Create a client + client = kms_v1.EkmServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.VerifyConnectivityRequest( + name="name_value", + ) + + # Make the request + response = await client.verify_connectivity(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_VerifyConnectivity_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py new file mode 100644 index 000000000000..1ce849c0520e --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for VerifyConnectivity +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_EkmService_VerifyConnectivity_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_verify_connectivity(): + # Create a client + client = kms_v1.EkmServiceClient() + + # Initialize request argument(s) + request = kms_v1.VerifyConnectivityRequest( + name="name_value", + ) + + # Make the request + response = client.verify_connectivity(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_EkmService_VerifyConnectivity_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py new file mode 100644 index 000000000000..0276698153e2 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AsymmetricDecrypt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_asymmetric_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.AsymmetricDecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + ) + + # Make the request + response = await client.asymmetric_decrypt(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py new file mode 100644 index 000000000000..f42b4ed1668f --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AsymmetricDecrypt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_asymmetric_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.AsymmetricDecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + ) + + # Make the request + response = client.asymmetric_decrypt(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py new file mode 100644 index 000000000000..1039bdc4ee07 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AsymmetricSign +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_AsymmetricSign_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_asymmetric_sign(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.AsymmetricSignRequest( + name="name_value", + ) + + # Make the request + response = await client.asymmetric_sign(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_AsymmetricSign_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py new file mode 100644 index 000000000000..e2a99a9f4da9 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AsymmetricSign +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_AsymmetricSign_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_asymmetric_sign(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.AsymmetricSignRequest( + name="name_value", + ) + + # Make the request + response = client.asymmetric_sign(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_AsymmetricSign_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_async.py new file mode 100644 index 000000000000..f2bf2b416d4e --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCryptoKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_create_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.CreateCryptoKeyRequest( + parent="parent_value", + crypto_key_id="crypto_key_id_value", + ) + + # Make the request + response = await client.create_crypto_key(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py new file mode 100644 index 000000000000..c1bc6cbe4d55 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCryptoKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_create_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.CreateCryptoKeyRequest( + parent="parent_value", + crypto_key_id="crypto_key_id_value", + ) + + # Make the request + response = client.create_crypto_key(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py new file mode 100644 index 000000000000..017d5d7f0ffd --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_create_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.CreateCryptoKeyVersionRequest( + parent="parent_value", + ) + + # Make the request + response = await client.create_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py new file mode 100644 index 000000000000..ad0ef21ebc81 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_create_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.CreateCryptoKeyVersionRequest( + parent="parent_value", + ) + + # Make the request + response = client.create_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py new file mode 100644 index 000000000000..662876ffc8de --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateImportJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_CreateImportJob_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_create_import_job(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + import_job = kms_v1.ImportJob() + import_job.import_method = "RSA_OAEP_4096_SHA256" + import_job.protection_level = "EXTERNAL_VPC" + + request = kms_v1.CreateImportJobRequest( + parent="parent_value", + import_job_id="import_job_id_value", + import_job=import_job, + ) + + # Make the request + response = await client.create_import_job(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_CreateImportJob_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py new file mode 100644 index 000000000000..86f5887b9b19 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateImportJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_CreateImportJob_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_create_import_job(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + import_job = kms_v1.ImportJob() + import_job.import_method = "RSA_OAEP_4096_SHA256" + import_job.protection_level = "EXTERNAL_VPC" + + request = kms_v1.CreateImportJobRequest( + parent="parent_value", + import_job_id="import_job_id_value", + import_job=import_job, + ) + + # Make the request + response = client.create_import_job(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_CreateImportJob_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_async.py new file mode 100644 index 000000000000..40bc57c5850a --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateKeyRing +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_CreateKeyRing_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_create_key_ring(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.CreateKeyRingRequest( + parent="parent_value", + key_ring_id="key_ring_id_value", + ) + + # Make the request + response = await client.create_key_ring(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_CreateKeyRing_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_sync.py new file mode 100644 index 000000000000..736928f89f04 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateKeyRing +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_CreateKeyRing_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_create_key_ring(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.CreateKeyRingRequest( + parent="parent_value", + key_ring_id="key_ring_id_value", + ) + + # Make the request + response = client.create_key_ring(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_CreateKeyRing_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_async.py new file mode 100644 index 000000000000..f691ae9aa828 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Decrypt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_Decrypt_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.DecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + ) + + # Make the request + response = await client.decrypt(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_Decrypt_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_sync.py new file mode 100644 index 000000000000..49fc5586472d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Decrypt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_Decrypt_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.DecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + ) + + # Make the request + response = client.decrypt(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_Decrypt_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py new file mode 100644 index 000000000000..3f7b361ee2c9 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DestroyCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_destroy_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.DestroyCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.destroy_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py new file mode 100644 index 000000000000..6b21af5853a9 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DestroyCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_destroy_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.DestroyCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = client.destroy_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_async.py new file mode 100644 index 000000000000..1610fe4564ac --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Encrypt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_Encrypt_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_encrypt(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.EncryptRequest( + name="name_value", + plaintext=b'plaintext_blob', + ) + + # Make the request + response = await client.encrypt(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_Encrypt_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_sync.py new file mode 100644 index 000000000000..b3cfa5969cd0 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for Encrypt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_Encrypt_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_encrypt(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.EncryptRequest( + name="name_value", + plaintext=b'plaintext_blob', + ) + + # Make the request + response = client.encrypt(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_Encrypt_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py new file mode 100644 index 000000000000..36302635dc0d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateRandomBytes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_generate_random_bytes(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GenerateRandomBytesRequest( + ) + + # Make the request + response = await client.generate_random_bytes(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py new file mode 100644 index 000000000000..58d57585b1d2 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateRandomBytes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_generate_random_bytes(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GenerateRandomBytesRequest( + ) + + # Make the request + response = client.generate_random_bytes(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_async.py new file mode 100644 index 000000000000..28e6ee8c09cb --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCryptoKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GetCryptoKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_get_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetCryptoKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_crypto_key(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GetCryptoKey_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py new file mode 100644 index 000000000000..98c022e4110a --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCryptoKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GetCryptoKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_get_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetCryptoKeyRequest( + name="name_value", + ) + + # Make the request + response = client.get_crypto_key(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GetCryptoKey_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py new file mode 100644 index 000000000000..0b5b907c76af --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_get_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py new file mode 100644 index 000000000000..3f06a8ddaef8 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_get_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = client.get_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_async.py new file mode 100644 index 000000000000..8fb0f45dab95 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetImportJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GetImportJob_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_get_import_job(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetImportJobRequest( + name="name_value", + ) + + # Make the request + response = await client.get_import_job(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GetImportJob_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_sync.py new file mode 100644 index 000000000000..c3cbf2233ced --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetImportJob +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GetImportJob_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_get_import_job(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetImportJobRequest( + name="name_value", + ) + + # Make the request + response = client.get_import_job(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GetImportJob_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_async.py new file mode 100644 index 000000000000..88905b3c9428 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetKeyRing +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GetKeyRing_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_get_key_ring(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetKeyRingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_key_ring(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GetKeyRing_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_sync.py new file mode 100644 index 000000000000..eb7c44e6b68e --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetKeyRing +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GetKeyRing_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_get_key_ring(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetKeyRingRequest( + name="name_value", + ) + + # Make the request + response = client.get_key_ring(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GetKeyRing_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_async.py new file mode 100644 index 000000000000..3086b8d6b6f7 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPublicKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GetPublicKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_get_public_key(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.GetPublicKeyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_public_key(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GetPublicKey_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_sync.py new file mode 100644 index 000000000000..312dcf004425 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPublicKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_GetPublicKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_get_public_key(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.GetPublicKeyRequest( + name="name_value", + ) + + # Make the request + response = client.get_public_key(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_GetPublicKey_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py new file mode 100644 index 000000000000..b7ab7f35c87d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_import_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ImportCryptoKeyVersionRequest( + rsa_aes_wrapped_key=b'rsa_aes_wrapped_key_blob', + parent="parent_value", + algorithm="EXTERNAL_SYMMETRIC_ENCRYPTION", + import_job="import_job_value", + ) + + # Make the request + response = await client.import_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py new file mode 100644 index 000000000000..cf0102d4121d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ImportCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_import_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ImportCryptoKeyVersionRequest( + rsa_aes_wrapped_key=b'rsa_aes_wrapped_key_blob', + parent="parent_value", + algorithm="EXTERNAL_SYMMETRIC_ENCRYPTION", + import_job="import_job_value", + ) + + # Make the request + response = client.import_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py new file mode 100644 index 000000000000..55bf1e3276fc --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCryptoKeyVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_list_crypto_key_versions(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListCryptoKeyVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crypto_key_versions(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py new file mode 100644 index 000000000000..37d7ded635b2 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCryptoKeyVersions +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_list_crypto_key_versions(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ListCryptoKeyVersionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crypto_key_versions(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py new file mode 100644 index 000000000000..3c090ebdc3e4 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCryptoKeys +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_list_crypto_keys(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListCryptoKeysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crypto_keys(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py new file mode 100644 index 000000000000..603c44280859 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListCryptoKeys +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_list_crypto_keys(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ListCryptoKeysRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_crypto_keys(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_async.py new file mode 100644 index 000000000000..53e15d99d257 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListImportJobs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ListImportJobs_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_list_import_jobs(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListImportJobsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_import_jobs(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_ListImportJobs_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py new file mode 100644 index 000000000000..981b33b05542 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListImportJobs +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ListImportJobs_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_list_import_jobs(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ListImportJobsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_import_jobs(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_ListImportJobs_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_async.py new file mode 100644 index 000000000000..d9bab55db774 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListKeyRings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ListKeyRings_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_list_key_rings(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ListKeyRingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_rings(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_ListKeyRings_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_sync.py new file mode 100644 index 000000000000..1440579645ce --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListKeyRings +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ListKeyRings_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_list_key_rings(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ListKeyRingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_key_rings(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_ListKeyRings_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_async.py new file mode 100644 index 000000000000..deb3ae7bef8a --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MacSign +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_MacSign_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_mac_sign(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.MacSignRequest( + name="name_value", + data=b'data_blob', + ) + + # Make the request + response = await client.mac_sign(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_MacSign_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_sync.py new file mode 100644 index 000000000000..c86d67b11ca8 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MacSign +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_MacSign_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_mac_sign(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.MacSignRequest( + name="name_value", + data=b'data_blob', + ) + + # Make the request + response = client.mac_sign(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_MacSign_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_async.py new file mode 100644 index 000000000000..88cd1afc72d1 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MacVerify +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_MacVerify_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_mac_verify(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.MacVerifyRequest( + name="name_value", + data=b'data_blob', + mac=b'mac_blob', + ) + + # Make the request + response = await client.mac_verify(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_MacVerify_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_sync.py new file mode 100644 index 000000000000..4e884e7ead1e --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for MacVerify +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_MacVerify_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_mac_verify(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.MacVerifyRequest( + name="name_value", + data=b'data_blob', + mac=b'mac_blob', + ) + + # Make the request + response = client.mac_verify(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_MacVerify_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_async.py new file mode 100644 index 000000000000..85327867bde0 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RawDecrypt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_RawDecrypt_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_raw_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.RawDecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + initialization_vector=b'initialization_vector_blob', + ) + + # Make the request + response = await client.raw_decrypt(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_RawDecrypt_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py new file mode 100644 index 000000000000..516eb485779b --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RawDecrypt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_RawDecrypt_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_raw_decrypt(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.RawDecryptRequest( + name="name_value", + ciphertext=b'ciphertext_blob', + initialization_vector=b'initialization_vector_blob', + ) + + # Make the request + response = client.raw_decrypt(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_RawDecrypt_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_async.py new file mode 100644 index 000000000000..0dd788632a8e --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RawEncrypt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_RawEncrypt_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_raw_encrypt(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.RawEncryptRequest( + name="name_value", + plaintext=b'plaintext_blob', + ) + + # Make the request + response = await client.raw_encrypt(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_RawEncrypt_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py new file mode 100644 index 000000000000..b6fa3e7ea53f --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RawEncrypt +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_RawEncrypt_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_raw_encrypt(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.RawEncryptRequest( + name="name_value", + plaintext=b'plaintext_blob', + ) + + # Make the request + response = client.raw_encrypt(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_RawEncrypt_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py new file mode 100644 index 000000000000..d66756fc32f8 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_restore_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.RestoreCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = await client.restore_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py new file mode 100644 index 000000000000..ae7c6d2aa877 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RestoreCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_restore_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.RestoreCryptoKeyVersionRequest( + name="name_value", + ) + + # Make the request + response = client.restore_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_async.py new file mode 100644 index 000000000000..d627815cc24d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCryptoKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_update_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyRequest( + ) + + # Make the request + response = await client.update_crypto_key(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py new file mode 100644 index 000000000000..ccd953a70e17 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCryptoKeyPrimaryVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_update_crypto_key_primary_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyPrimaryVersionRequest( + name="name_value", + crypto_key_version_id="crypto_key_version_id_value", + ) + + # Make the request + response = await client.update_crypto_key_primary_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py new file mode 100644 index 000000000000..e7f3cbe542de --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCryptoKeyPrimaryVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_update_crypto_key_primary_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyPrimaryVersionRequest( + name="name_value", + crypto_key_version_id="crypto_key_version_id_value", + ) + + # Make the request + response = client.update_crypto_key_primary_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py new file mode 100644 index 000000000000..6fa8b692bd6e --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCryptoKey +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_update_crypto_key(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyRequest( + ) + + # Make the request + response = client.update_crypto_key(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py new file mode 100644 index 000000000000..d11fbe440196 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_update_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyVersionRequest( + ) + + # Make the request + response = await client.update_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py new file mode 100644 index 000000000000..bd1a3cbc23eb --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateCryptoKeyVersion +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-kms + + +# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +def sample_update_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.UpdateCryptoKeyVersionRequest( + ) + + # Make the request + response = client.update_crypto_key_version(request=request) + + # Handle the response + print(response) + +# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json new file mode 100644 index 000000000000..a5e165bff4c4 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json @@ -0,0 +1,6800 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.cloud.kms.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-cloud-kms", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient", + "shortName": "AutokeyAdminAsyncClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient.get_autokey_config", + "method": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig", + "service": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin", + "shortName": "AutokeyAdmin" + }, + "shortName": "GetAutokeyConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetAutokeyConfigRequest" + }, + { + "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.kms_v1.types.AutokeyConfig", + "shortName": "get_autokey_config" + }, + "description": "Sample for GetAutokeyConfig", + "file": "cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.AutokeyAdminClient", + "shortName": "AutokeyAdminClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyAdminClient.get_autokey_config", + "method": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig", + "service": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin", + "shortName": "AutokeyAdmin" + }, + "shortName": "GetAutokeyConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetAutokeyConfigRequest" + }, + { + "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.kms_v1.types.AutokeyConfig", + "shortName": "get_autokey_config" + }, + "description": "Sample for GetAutokeyConfig", + "file": "cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient", + "shortName": "AutokeyAdminAsyncClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient.show_effective_autokey_config", + "method": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig", + "service": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin", + "shortName": "AutokeyAdmin" + }, + "shortName": "ShowEffectiveAutokeyConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ShowEffectiveAutokeyConfigRequest" + }, + { + "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.kms_v1.types.ShowEffectiveAutokeyConfigResponse", + "shortName": "show_effective_autokey_config" + }, + "description": "Sample for ShowEffectiveAutokeyConfig", + "file": "cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.AutokeyAdminClient", + "shortName": "AutokeyAdminClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyAdminClient.show_effective_autokey_config", + "method": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig", + "service": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin", + "shortName": "AutokeyAdmin" + }, + "shortName": "ShowEffectiveAutokeyConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ShowEffectiveAutokeyConfigRequest" + }, + { + "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.kms_v1.types.ShowEffectiveAutokeyConfigResponse", + "shortName": "show_effective_autokey_config" + }, + "description": "Sample for ShowEffectiveAutokeyConfig", + "file": "cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient", + "shortName": "AutokeyAdminAsyncClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient.update_autokey_config", + "method": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig", + "service": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin", + "shortName": "AutokeyAdmin" + }, + "shortName": "UpdateAutokeyConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateAutokeyConfigRequest" + }, + { + "name": "autokey_config", + "type": "google.cloud.kms_v1.types.AutokeyConfig" + }, + { + "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.cloud.kms_v1.types.AutokeyConfig", + "shortName": "update_autokey_config" + }, + "description": "Sample for UpdateAutokeyConfig", + "file": "cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.AutokeyAdminClient", + "shortName": "AutokeyAdminClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyAdminClient.update_autokey_config", + "method": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig", + "service": { + "fullName": "google.cloud.kms.v1.AutokeyAdmin", + "shortName": "AutokeyAdmin" + }, + "shortName": "UpdateAutokeyConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateAutokeyConfigRequest" + }, + { + "name": "autokey_config", + "type": "google.cloud.kms_v1.types.AutokeyConfig" + }, + { + "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.cloud.kms_v1.types.AutokeyConfig", + "shortName": "update_autokey_config" + }, + "description": "Sample for UpdateAutokeyConfig", + "file": "cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.AutokeyAsyncClient", + "shortName": "AutokeyAsyncClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyAsyncClient.create_key_handle", + "method": { + "fullName": "google.cloud.kms.v1.Autokey.CreateKeyHandle", + "service": { + "fullName": "google.cloud.kms.v1.Autokey", + "shortName": "Autokey" + }, + "shortName": "CreateKeyHandle" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateKeyHandleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "key_handle", + "type": "google.cloud.kms_v1.types.KeyHandle" + }, + { + "name": "key_handle_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "create_key_handle" + }, + "description": "Sample for CreateKeyHandle", + "file": "cloudkms_v1_generated_autokey_create_key_handle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_Autokey_CreateKeyHandle_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_autokey_create_key_handle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.AutokeyClient", + "shortName": "AutokeyClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyClient.create_key_handle", + "method": { + "fullName": "google.cloud.kms.v1.Autokey.CreateKeyHandle", + "service": { + "fullName": "google.cloud.kms.v1.Autokey", + "shortName": "Autokey" + }, + "shortName": "CreateKeyHandle" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateKeyHandleRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "key_handle", + "type": "google.cloud.kms_v1.types.KeyHandle" + }, + { + "name": "key_handle_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "create_key_handle" + }, + "description": "Sample for CreateKeyHandle", + "file": "cloudkms_v1_generated_autokey_create_key_handle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_Autokey_CreateKeyHandle_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_autokey_create_key_handle_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.AutokeyAsyncClient", + "shortName": "AutokeyAsyncClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyAsyncClient.get_key_handle", + "method": { + "fullName": "google.cloud.kms.v1.Autokey.GetKeyHandle", + "service": { + "fullName": "google.cloud.kms.v1.Autokey", + "shortName": "Autokey" + }, + "shortName": "GetKeyHandle" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetKeyHandleRequest" + }, + { + "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.kms_v1.types.KeyHandle", + "shortName": "get_key_handle" + }, + "description": "Sample for GetKeyHandle", + "file": "cloudkms_v1_generated_autokey_get_key_handle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_Autokey_GetKeyHandle_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": "cloudkms_v1_generated_autokey_get_key_handle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.AutokeyClient", + "shortName": "AutokeyClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyClient.get_key_handle", + "method": { + "fullName": "google.cloud.kms.v1.Autokey.GetKeyHandle", + "service": { + "fullName": "google.cloud.kms.v1.Autokey", + "shortName": "Autokey" + }, + "shortName": "GetKeyHandle" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetKeyHandleRequest" + }, + { + "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.kms_v1.types.KeyHandle", + "shortName": "get_key_handle" + }, + "description": "Sample for GetKeyHandle", + "file": "cloudkms_v1_generated_autokey_get_key_handle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_Autokey_GetKeyHandle_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": "cloudkms_v1_generated_autokey_get_key_handle_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.AutokeyAsyncClient", + "shortName": "AutokeyAsyncClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyAsyncClient.list_key_handles", + "method": { + "fullName": "google.cloud.kms.v1.Autokey.ListKeyHandles", + "service": { + "fullName": "google.cloud.kms.v1.Autokey", + "shortName": "Autokey" + }, + "shortName": "ListKeyHandles" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListKeyHandlesRequest" + }, + { + "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.kms_v1.services.autokey.pagers.ListKeyHandlesAsyncPager", + "shortName": "list_key_handles" + }, + "description": "Sample for ListKeyHandles", + "file": "cloudkms_v1_generated_autokey_list_key_handles_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_Autokey_ListKeyHandles_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_autokey_list_key_handles_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.AutokeyClient", + "shortName": "AutokeyClient" + }, + "fullName": "google.cloud.kms_v1.AutokeyClient.list_key_handles", + "method": { + "fullName": "google.cloud.kms.v1.Autokey.ListKeyHandles", + "service": { + "fullName": "google.cloud.kms.v1.Autokey", + "shortName": "Autokey" + }, + "shortName": "ListKeyHandles" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListKeyHandlesRequest" + }, + { + "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.kms_v1.services.autokey.pagers.ListKeyHandlesPager", + "shortName": "list_key_handles" + }, + "description": "Sample for ListKeyHandles", + "file": "cloudkms_v1_generated_autokey_list_key_handles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_Autokey_ListKeyHandles_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_autokey_list_key_handles_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", + "shortName": "EkmServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.create_ekm_connection", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.CreateEkmConnection", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "CreateEkmConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateEkmConnectionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "ekm_connection_id", + "type": "str" + }, + { + "name": "ekm_connection", + "type": "google.cloud.kms_v1.types.EkmConnection" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.EkmConnection", + "shortName": "create_ekm_connection" + }, + "description": "Sample for CreateEkmConnection", + "file": "cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_CreateEkmConnection_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceClient", + "shortName": "EkmServiceClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceClient.create_ekm_connection", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.CreateEkmConnection", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "CreateEkmConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateEkmConnectionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "ekm_connection_id", + "type": "str" + }, + { + "name": "ekm_connection", + "type": "google.cloud.kms_v1.types.EkmConnection" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.EkmConnection", + "shortName": "create_ekm_connection" + }, + "description": "Sample for CreateEkmConnection", + "file": "cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_CreateEkmConnection_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", + "shortName": "EkmServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.get_ekm_config", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.GetEkmConfig", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "GetEkmConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetEkmConfigRequest" + }, + { + "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.kms_v1.types.EkmConfig", + "shortName": "get_ekm_config" + }, + "description": "Sample for GetEkmConfig", + "file": "cloudkms_v1_generated_ekm_service_get_ekm_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_GetEkmConfig_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": "cloudkms_v1_generated_ekm_service_get_ekm_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceClient", + "shortName": "EkmServiceClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceClient.get_ekm_config", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.GetEkmConfig", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "GetEkmConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetEkmConfigRequest" + }, + { + "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.kms_v1.types.EkmConfig", + "shortName": "get_ekm_config" + }, + "description": "Sample for GetEkmConfig", + "file": "cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_GetEkmConfig_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": "cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", + "shortName": "EkmServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.get_ekm_connection", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.GetEkmConnection", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "GetEkmConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetEkmConnectionRequest" + }, + { + "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.kms_v1.types.EkmConnection", + "shortName": "get_ekm_connection" + }, + "description": "Sample for GetEkmConnection", + "file": "cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_GetEkmConnection_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": "cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceClient", + "shortName": "EkmServiceClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceClient.get_ekm_connection", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.GetEkmConnection", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "GetEkmConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetEkmConnectionRequest" + }, + { + "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.kms_v1.types.EkmConnection", + "shortName": "get_ekm_connection" + }, + "description": "Sample for GetEkmConnection", + "file": "cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_GetEkmConnection_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": "cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", + "shortName": "EkmServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.list_ekm_connections", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.ListEkmConnections", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "ListEkmConnections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListEkmConnectionsRequest" + }, + { + "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.kms_v1.services.ekm_service.pagers.ListEkmConnectionsAsyncPager", + "shortName": "list_ekm_connections" + }, + "description": "Sample for ListEkmConnections", + "file": "cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_ListEkmConnections_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceClient", + "shortName": "EkmServiceClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceClient.list_ekm_connections", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.ListEkmConnections", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "ListEkmConnections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListEkmConnectionsRequest" + }, + { + "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.kms_v1.services.ekm_service.pagers.ListEkmConnectionsPager", + "shortName": "list_ekm_connections" + }, + "description": "Sample for ListEkmConnections", + "file": "cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_ListEkmConnections_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", + "shortName": "EkmServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.update_ekm_config", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.UpdateEkmConfig", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "UpdateEkmConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateEkmConfigRequest" + }, + { + "name": "ekm_config", + "type": "google.cloud.kms_v1.types.EkmConfig" + }, + { + "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.cloud.kms_v1.types.EkmConfig", + "shortName": "update_ekm_config" + }, + "description": "Sample for UpdateEkmConfig", + "file": "cloudkms_v1_generated_ekm_service_update_ekm_config_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_UpdateEkmConfig_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": "cloudkms_v1_generated_ekm_service_update_ekm_config_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceClient", + "shortName": "EkmServiceClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceClient.update_ekm_config", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.UpdateEkmConfig", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "UpdateEkmConfig" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateEkmConfigRequest" + }, + { + "name": "ekm_config", + "type": "google.cloud.kms_v1.types.EkmConfig" + }, + { + "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.cloud.kms_v1.types.EkmConfig", + "shortName": "update_ekm_config" + }, + "description": "Sample for UpdateEkmConfig", + "file": "cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_UpdateEkmConfig_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": "cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", + "shortName": "EkmServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.update_ekm_connection", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.UpdateEkmConnection", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "UpdateEkmConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateEkmConnectionRequest" + }, + { + "name": "ekm_connection", + "type": "google.cloud.kms_v1.types.EkmConnection" + }, + { + "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.cloud.kms_v1.types.EkmConnection", + "shortName": "update_ekm_connection" + }, + "description": "Sample for UpdateEkmConnection", + "file": "cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_UpdateEkmConnection_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": "cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceClient", + "shortName": "EkmServiceClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceClient.update_ekm_connection", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.UpdateEkmConnection", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "UpdateEkmConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateEkmConnectionRequest" + }, + { + "name": "ekm_connection", + "type": "google.cloud.kms_v1.types.EkmConnection" + }, + { + "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.cloud.kms_v1.types.EkmConnection", + "shortName": "update_ekm_connection" + }, + "description": "Sample for UpdateEkmConnection", + "file": "cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_UpdateEkmConnection_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": "cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", + "shortName": "EkmServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.verify_connectivity", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.VerifyConnectivity", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "VerifyConnectivity" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.VerifyConnectivityRequest" + }, + { + "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.kms_v1.types.VerifyConnectivityResponse", + "shortName": "verify_connectivity" + }, + "description": "Sample for VerifyConnectivity", + "file": "cloudkms_v1_generated_ekm_service_verify_connectivity_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_VerifyConnectivity_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": "cloudkms_v1_generated_ekm_service_verify_connectivity_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.EkmServiceClient", + "shortName": "EkmServiceClient" + }, + "fullName": "google.cloud.kms_v1.EkmServiceClient.verify_connectivity", + "method": { + "fullName": "google.cloud.kms.v1.EkmService.VerifyConnectivity", + "service": { + "fullName": "google.cloud.kms.v1.EkmService", + "shortName": "EkmService" + }, + "shortName": "VerifyConnectivity" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.VerifyConnectivityRequest" + }, + { + "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.kms_v1.types.VerifyConnectivityResponse", + "shortName": "verify_connectivity" + }, + "description": "Sample for VerifyConnectivity", + "file": "cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_EkmService_VerifyConnectivity_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": "cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.asymmetric_decrypt", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "AsymmetricDecrypt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.AsymmetricDecryptRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "ciphertext", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.AsymmetricDecryptResponse", + "shortName": "asymmetric_decrypt" + }, + "description": "Sample for AsymmetricDecrypt", + "file": "cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.asymmetric_decrypt", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "AsymmetricDecrypt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.AsymmetricDecryptRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "ciphertext", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.AsymmetricDecryptResponse", + "shortName": "asymmetric_decrypt" + }, + "description": "Sample for AsymmetricDecrypt", + "file": "cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.asymmetric_sign", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.AsymmetricSign", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "AsymmetricSign" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.AsymmetricSignRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "digest", + "type": "google.cloud.kms_v1.types.Digest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.AsymmetricSignResponse", + "shortName": "asymmetric_sign" + }, + "description": "Sample for AsymmetricSign", + "file": "cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_AsymmetricSign_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": "cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.asymmetric_sign", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.AsymmetricSign", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "AsymmetricSign" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.AsymmetricSignRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "digest", + "type": "google.cloud.kms_v1.types.Digest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.AsymmetricSignResponse", + "shortName": "asymmetric_sign" + }, + "description": "Sample for AsymmetricSign", + "file": "cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_AsymmetricSign_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": "cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.create_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "CreateCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "crypto_key_version", + "type": "google.cloud.kms_v1.types.CryptoKeyVersion" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.CryptoKeyVersion", + "shortName": "create_crypto_key_version" + }, + "description": "Sample for CreateCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.create_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "CreateCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "crypto_key_version", + "type": "google.cloud.kms_v1.types.CryptoKeyVersion" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.CryptoKeyVersion", + "shortName": "create_crypto_key_version" + }, + "description": "Sample for CreateCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.create_crypto_key", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.CreateCryptoKey", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "CreateCryptoKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateCryptoKeyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "crypto_key_id", + "type": "str" + }, + { + "name": "crypto_key", + "type": "google.cloud.kms_v1.types.CryptoKey" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.CryptoKey", + "shortName": "create_crypto_key" + }, + "description": "Sample for CreateCryptoKey", + "file": "cloudkms_v1_generated_key_management_service_create_crypto_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_create_crypto_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.create_crypto_key", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.CreateCryptoKey", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "CreateCryptoKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateCryptoKeyRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "crypto_key_id", + "type": "str" + }, + { + "name": "crypto_key", + "type": "google.cloud.kms_v1.types.CryptoKey" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.CryptoKey", + "shortName": "create_crypto_key" + }, + "description": "Sample for CreateCryptoKey", + "file": "cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.create_import_job", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.CreateImportJob", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "CreateImportJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateImportJobRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "import_job_id", + "type": "str" + }, + { + "name": "import_job", + "type": "google.cloud.kms_v1.types.ImportJob" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.ImportJob", + "shortName": "create_import_job" + }, + "description": "Sample for CreateImportJob", + "file": "cloudkms_v1_generated_key_management_service_create_import_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateImportJob_async", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_create_import_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.create_import_job", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.CreateImportJob", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "CreateImportJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateImportJobRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "import_job_id", + "type": "str" + }, + { + "name": "import_job", + "type": "google.cloud.kms_v1.types.ImportJob" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.ImportJob", + "shortName": "create_import_job" + }, + "description": "Sample for CreateImportJob", + "file": "cloudkms_v1_generated_key_management_service_create_import_job_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateImportJob_sync", + "segments": [ + { + "end": 57, + "start": 27, + "type": "FULL" + }, + { + "end": 57, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 54, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 58, + "start": 55, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_create_import_job_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.create_key_ring", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.CreateKeyRing", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "CreateKeyRing" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateKeyRingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "key_ring_id", + "type": "str" + }, + { + "name": "key_ring", + "type": "google.cloud.kms_v1.types.KeyRing" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.KeyRing", + "shortName": "create_key_ring" + }, + "description": "Sample for CreateKeyRing", + "file": "cloudkms_v1_generated_key_management_service_create_key_ring_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateKeyRing_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_create_key_ring_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.create_key_ring", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.CreateKeyRing", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "CreateKeyRing" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.CreateKeyRingRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "key_ring_id", + "type": "str" + }, + { + "name": "key_ring", + "type": "google.cloud.kms_v1.types.KeyRing" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.KeyRing", + "shortName": "create_key_ring" + }, + "description": "Sample for CreateKeyRing", + "file": "cloudkms_v1_generated_key_management_service_create_key_ring_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateKeyRing_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_create_key_ring_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.decrypt", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.Decrypt", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "Decrypt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.DecryptRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "ciphertext", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.DecryptResponse", + "shortName": "decrypt" + }, + "description": "Sample for Decrypt", + "file": "cloudkms_v1_generated_key_management_service_decrypt_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_Decrypt_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_decrypt_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.decrypt", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.Decrypt", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "Decrypt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.DecryptRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "ciphertext", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.DecryptResponse", + "shortName": "decrypt" + }, + "description": "Sample for Decrypt", + "file": "cloudkms_v1_generated_key_management_service_decrypt_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_Decrypt_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_decrypt_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.destroy_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "DestroyCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest" + }, + { + "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.kms_v1.types.CryptoKeyVersion", + "shortName": "destroy_crypto_key_version" + }, + "description": "Sample for DestroyCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.destroy_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "DestroyCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest" + }, + { + "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.kms_v1.types.CryptoKeyVersion", + "shortName": "destroy_crypto_key_version" + }, + "description": "Sample for DestroyCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.encrypt", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.Encrypt", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "Encrypt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.EncryptRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "plaintext", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.EncryptResponse", + "shortName": "encrypt" + }, + "description": "Sample for Encrypt", + "file": "cloudkms_v1_generated_key_management_service_encrypt_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_Encrypt_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_encrypt_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.encrypt", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.Encrypt", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "Encrypt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.EncryptRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "plaintext", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.EncryptResponse", + "shortName": "encrypt" + }, + "description": "Sample for Encrypt", + "file": "cloudkms_v1_generated_key_management_service_encrypt_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_Encrypt_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_encrypt_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.generate_random_bytes", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GenerateRandomBytes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GenerateRandomBytesRequest" + }, + { + "name": "location", + "type": "str" + }, + { + "name": "length_bytes", + "type": "int" + }, + { + "name": "protection_level", + "type": "google.cloud.kms_v1.types.ProtectionLevel" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.GenerateRandomBytesResponse", + "shortName": "generate_random_bytes" + }, + "description": "Sample for GenerateRandomBytes", + "file": "cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_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": "cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.generate_random_bytes", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GenerateRandomBytes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GenerateRandomBytesRequest" + }, + { + "name": "location", + "type": "str" + }, + { + "name": "length_bytes", + "type": "int" + }, + { + "name": "protection_level", + "type": "google.cloud.kms_v1.types.ProtectionLevel" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.GenerateRandomBytesResponse", + "shortName": "generate_random_bytes" + }, + "description": "Sample for GenerateRandomBytes", + "file": "cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_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": "cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.get_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GetCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetCryptoKeyVersionRequest" + }, + { + "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.kms_v1.types.CryptoKeyVersion", + "shortName": "get_crypto_key_version" + }, + "description": "Sample for GetCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.get_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GetCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetCryptoKeyVersionRequest" + }, + { + "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.kms_v1.types.CryptoKeyVersion", + "shortName": "get_crypto_key_version" + }, + "description": "Sample for GetCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.get_crypto_key", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GetCryptoKey", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GetCryptoKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetCryptoKeyRequest" + }, + { + "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.kms_v1.types.CryptoKey", + "shortName": "get_crypto_key" + }, + "description": "Sample for GetCryptoKey", + "file": "cloudkms_v1_generated_key_management_service_get_crypto_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GetCryptoKey_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": "cloudkms_v1_generated_key_management_service_get_crypto_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.get_crypto_key", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GetCryptoKey", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GetCryptoKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetCryptoKeyRequest" + }, + { + "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.kms_v1.types.CryptoKey", + "shortName": "get_crypto_key" + }, + "description": "Sample for GetCryptoKey", + "file": "cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GetCryptoKey_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": "cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.get_import_job", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GetImportJob", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GetImportJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetImportJobRequest" + }, + { + "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.kms_v1.types.ImportJob", + "shortName": "get_import_job" + }, + "description": "Sample for GetImportJob", + "file": "cloudkms_v1_generated_key_management_service_get_import_job_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GetImportJob_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": "cloudkms_v1_generated_key_management_service_get_import_job_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.get_import_job", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GetImportJob", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GetImportJob" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetImportJobRequest" + }, + { + "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.kms_v1.types.ImportJob", + "shortName": "get_import_job" + }, + "description": "Sample for GetImportJob", + "file": "cloudkms_v1_generated_key_management_service_get_import_job_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GetImportJob_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": "cloudkms_v1_generated_key_management_service_get_import_job_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.get_key_ring", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GetKeyRing", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GetKeyRing" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetKeyRingRequest" + }, + { + "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.kms_v1.types.KeyRing", + "shortName": "get_key_ring" + }, + "description": "Sample for GetKeyRing", + "file": "cloudkms_v1_generated_key_management_service_get_key_ring_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GetKeyRing_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": "cloudkms_v1_generated_key_management_service_get_key_ring_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.get_key_ring", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GetKeyRing", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GetKeyRing" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetKeyRingRequest" + }, + { + "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.kms_v1.types.KeyRing", + "shortName": "get_key_ring" + }, + "description": "Sample for GetKeyRing", + "file": "cloudkms_v1_generated_key_management_service_get_key_ring_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GetKeyRing_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": "cloudkms_v1_generated_key_management_service_get_key_ring_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.get_public_key", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GetPublicKey", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GetPublicKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetPublicKeyRequest" + }, + { + "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.kms_v1.types.PublicKey", + "shortName": "get_public_key" + }, + "description": "Sample for GetPublicKey", + "file": "cloudkms_v1_generated_key_management_service_get_public_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GetPublicKey_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": "cloudkms_v1_generated_key_management_service_get_public_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.get_public_key", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.GetPublicKey", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "GetPublicKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.GetPublicKeyRequest" + }, + { + "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.kms_v1.types.PublicKey", + "shortName": "get_public_key" + }, + "description": "Sample for GetPublicKey", + "file": "cloudkms_v1_generated_key_management_service_get_public_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_GetPublicKey_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": "cloudkms_v1_generated_key_management_service_get_public_key_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.import_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ImportCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.CryptoKeyVersion", + "shortName": "import_crypto_key_version" + }, + "description": "Sample for ImportCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_async", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.import_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ImportCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.CryptoKeyVersion", + "shortName": "import_crypto_key_version" + }, + "description": "Sample for ImportCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.list_crypto_key_versions", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ListCryptoKeyVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest" + }, + { + "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.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsAsyncPager", + "shortName": "list_crypto_key_versions" + }, + "description": "Sample for ListCryptoKeyVersions", + "file": "cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.list_crypto_key_versions", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ListCryptoKeyVersions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest" + }, + { + "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.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsPager", + "shortName": "list_crypto_key_versions" + }, + "description": "Sample for ListCryptoKeyVersions", + "file": "cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.list_crypto_keys", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ListCryptoKeys", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ListCryptoKeys" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListCryptoKeysRequest" + }, + { + "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.kms_v1.services.key_management_service.pagers.ListCryptoKeysAsyncPager", + "shortName": "list_crypto_keys" + }, + "description": "Sample for ListCryptoKeys", + "file": "cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.list_crypto_keys", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ListCryptoKeys", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ListCryptoKeys" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListCryptoKeysRequest" + }, + { + "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.kms_v1.services.key_management_service.pagers.ListCryptoKeysPager", + "shortName": "list_crypto_keys" + }, + "description": "Sample for ListCryptoKeys", + "file": "cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.list_import_jobs", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ListImportJobs", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ListImportJobs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListImportJobsRequest" + }, + { + "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.kms_v1.services.key_management_service.pagers.ListImportJobsAsyncPager", + "shortName": "list_import_jobs" + }, + "description": "Sample for ListImportJobs", + "file": "cloudkms_v1_generated_key_management_service_list_import_jobs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ListImportJobs_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_list_import_jobs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.list_import_jobs", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ListImportJobs", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ListImportJobs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListImportJobsRequest" + }, + { + "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.kms_v1.services.key_management_service.pagers.ListImportJobsPager", + "shortName": "list_import_jobs" + }, + "description": "Sample for ListImportJobs", + "file": "cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ListImportJobs_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.list_key_rings", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ListKeyRings", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ListKeyRings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListKeyRingsRequest" + }, + { + "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.kms_v1.services.key_management_service.pagers.ListKeyRingsAsyncPager", + "shortName": "list_key_rings" + }, + "description": "Sample for ListKeyRings", + "file": "cloudkms_v1_generated_key_management_service_list_key_rings_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ListKeyRings_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_list_key_rings_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.list_key_rings", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ListKeyRings", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ListKeyRings" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ListKeyRingsRequest" + }, + { + "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.kms_v1.services.key_management_service.pagers.ListKeyRingsPager", + "shortName": "list_key_rings" + }, + "description": "Sample for ListKeyRings", + "file": "cloudkms_v1_generated_key_management_service_list_key_rings_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ListKeyRings_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_list_key_rings_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.mac_sign", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.MacSign", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "MacSign" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.MacSignRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.MacSignResponse", + "shortName": "mac_sign" + }, + "description": "Sample for MacSign", + "file": "cloudkms_v1_generated_key_management_service_mac_sign_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_MacSign_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_mac_sign_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.mac_sign", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.MacSign", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "MacSign" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.MacSignRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.MacSignResponse", + "shortName": "mac_sign" + }, + "description": "Sample for MacSign", + "file": "cloudkms_v1_generated_key_management_service_mac_sign_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_MacSign_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_mac_sign_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.mac_verify", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.MacVerify", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "MacVerify" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.MacVerifyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "mac", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.MacVerifyResponse", + "shortName": "mac_verify" + }, + "description": "Sample for MacVerify", + "file": "cloudkms_v1_generated_key_management_service_mac_verify_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_MacVerify_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_mac_verify_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.mac_verify", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.MacVerify", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "MacVerify" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.MacVerifyRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "data", + "type": "bytes" + }, + { + "name": "mac", + "type": "bytes" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.MacVerifyResponse", + "shortName": "mac_verify" + }, + "description": "Sample for MacVerify", + "file": "cloudkms_v1_generated_key_management_service_mac_verify_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_MacVerify_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_mac_verify_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.raw_decrypt", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.RawDecrypt", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "RawDecrypt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.RawDecryptRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.RawDecryptResponse", + "shortName": "raw_decrypt" + }, + "description": "Sample for RawDecrypt", + "file": "cloudkms_v1_generated_key_management_service_raw_decrypt_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_RawDecrypt_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_raw_decrypt_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.raw_decrypt", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.RawDecrypt", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "RawDecrypt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.RawDecryptRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.RawDecryptResponse", + "shortName": "raw_decrypt" + }, + "description": "Sample for RawDecrypt", + "file": "cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_RawDecrypt_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.raw_encrypt", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.RawEncrypt", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "RawEncrypt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.RawEncryptRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.RawEncryptResponse", + "shortName": "raw_encrypt" + }, + "description": "Sample for RawEncrypt", + "file": "cloudkms_v1_generated_key_management_service_raw_encrypt_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_RawEncrypt_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_raw_encrypt_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.raw_encrypt", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.RawEncrypt", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "RawEncrypt" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.RawEncryptRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.RawEncryptResponse", + "shortName": "raw_encrypt" + }, + "description": "Sample for RawEncrypt", + "file": "cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_RawEncrypt_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.restore_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "RestoreCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest" + }, + { + "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.kms_v1.types.CryptoKeyVersion", + "shortName": "restore_crypto_key_version" + }, + "description": "Sample for RestoreCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.restore_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "RestoreCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest" + }, + { + "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.kms_v1.types.CryptoKeyVersion", + "shortName": "restore_crypto_key_version" + }, + "description": "Sample for RestoreCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.update_crypto_key_primary_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "UpdateCryptoKeyPrimaryVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "crypto_key_version_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.CryptoKey", + "shortName": "update_crypto_key_primary_version" + }, + "description": "Sample for UpdateCryptoKeyPrimaryVersion", + "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.update_crypto_key_primary_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "UpdateCryptoKeyPrimaryVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "crypto_key_version_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.kms_v1.types.CryptoKey", + "shortName": "update_crypto_key_primary_version" + }, + "description": "Sample for UpdateCryptoKeyPrimaryVersion", + "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.update_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "UpdateCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest" + }, + { + "name": "crypto_key_version", + "type": "google.cloud.kms_v1.types.CryptoKeyVersion" + }, + { + "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.cloud.kms_v1.types.CryptoKeyVersion", + "shortName": "update_crypto_key_version" + }, + "description": "Sample for UpdateCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.update_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "UpdateCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest" + }, + { + "name": "crypto_key_version", + "type": "google.cloud.kms_v1.types.CryptoKeyVersion" + }, + { + "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.cloud.kms_v1.types.CryptoKeyVersion", + "shortName": "update_crypto_key_version" + }, + "description": "Sample for UpdateCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.update_crypto_key", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "UpdateCryptoKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateCryptoKeyRequest" + }, + { + "name": "crypto_key", + "type": "google.cloud.kms_v1.types.CryptoKey" + }, + { + "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.cloud.kms_v1.types.CryptoKey", + "shortName": "update_crypto_key" + }, + "description": "Sample for UpdateCryptoKey", + "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_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": "cloudkms_v1_generated_key_management_service_update_crypto_key_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.update_crypto_key", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "UpdateCryptoKey" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.UpdateCryptoKeyRequest" + }, + { + "name": "crypto_key", + "type": "google.cloud.kms_v1.types.CryptoKey" + }, + { + "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.cloud.kms_v1.types.CryptoKey", + "shortName": "update_crypto_key" + }, + "description": "Sample for UpdateCryptoKey", + "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_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": "cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py" + } + ] +} diff --git a/owl-bot-staging/google-cloud-kms/v1/scripts/fixup_kms_v1_keywords.py b/owl-bot-staging/google-cloud-kms/v1/scripts/fixup_kms_v1_keywords.py new file mode 100644 index 000000000000..7a838e47d117 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/scripts/fixup_kms_v1_keywords.py @@ -0,0 +1,219 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class kmsCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'asymmetric_decrypt': ('name', 'ciphertext', 'ciphertext_crc32c', ), + 'asymmetric_sign': ('name', 'digest', 'digest_crc32c', 'data', 'data_crc32c', ), + 'create_crypto_key': ('parent', 'crypto_key_id', 'crypto_key', 'skip_initial_version_creation', ), + 'create_crypto_key_version': ('parent', 'crypto_key_version', ), + 'create_ekm_connection': ('parent', 'ekm_connection_id', 'ekm_connection', ), + 'create_import_job': ('parent', 'import_job_id', 'import_job', ), + 'create_key_handle': ('parent', 'key_handle', 'key_handle_id', ), + 'create_key_ring': ('parent', 'key_ring_id', 'key_ring', ), + 'decrypt': ('name', 'ciphertext', 'additional_authenticated_data', 'ciphertext_crc32c', 'additional_authenticated_data_crc32c', ), + 'destroy_crypto_key_version': ('name', ), + 'encrypt': ('name', 'plaintext', 'additional_authenticated_data', 'plaintext_crc32c', 'additional_authenticated_data_crc32c', ), + 'generate_random_bytes': ('location', 'length_bytes', 'protection_level', ), + 'get_autokey_config': ('name', ), + 'get_crypto_key': ('name', ), + 'get_crypto_key_version': ('name', ), + 'get_ekm_config': ('name', ), + 'get_ekm_connection': ('name', ), + 'get_import_job': ('name', ), + 'get_key_handle': ('name', ), + 'get_key_ring': ('name', ), + 'get_public_key': ('name', ), + 'import_crypto_key_version': ('parent', 'algorithm', 'import_job', 'crypto_key_version', 'wrapped_key', 'rsa_aes_wrapped_key', ), + 'list_crypto_keys': ('parent', 'page_size', 'page_token', 'version_view', 'filter', 'order_by', ), + 'list_crypto_key_versions': ('parent', 'page_size', 'page_token', 'view', 'filter', 'order_by', ), + 'list_ekm_connections': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_import_jobs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_key_handles': ('parent', 'page_size', 'page_token', 'filter', ), + 'list_key_rings': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'mac_sign': ('name', 'data', 'data_crc32c', ), + 'mac_verify': ('name', 'data', 'mac', 'data_crc32c', 'mac_crc32c', ), + 'raw_decrypt': ('name', 'ciphertext', 'initialization_vector', 'additional_authenticated_data', 'tag_length', 'ciphertext_crc32c', 'additional_authenticated_data_crc32c', 'initialization_vector_crc32c', ), + 'raw_encrypt': ('name', 'plaintext', 'additional_authenticated_data', 'plaintext_crc32c', 'additional_authenticated_data_crc32c', 'initialization_vector', 'initialization_vector_crc32c', ), + 'restore_crypto_key_version': ('name', ), + 'show_effective_autokey_config': ('parent', ), + 'update_autokey_config': ('autokey_config', 'update_mask', ), + 'update_crypto_key': ('crypto_key', 'update_mask', ), + 'update_crypto_key_primary_version': ('name', 'crypto_key_version_id', ), + 'update_crypto_key_version': ('crypto_key_version', 'update_mask', ), + 'update_ekm_config': ('ekm_config', 'update_mask', ), + 'update_ekm_connection': ('ekm_connection', 'update_mask', ), + 'verify_connectivity': ('name', ), + 'get_iam_policy': ('resource', 'options', ), + 'set_iam_policy': ('resource', 'policy', ), + 'test_iam_permissions': ('resource', 'permissions', ), + } + + 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=kmsCallTransformer(), +): + """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 kms 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-kms/v1/setup.py b/owl-bot-staging/google-cloud-kms/v1/setup.py new file mode 100644 index 000000000000..151f2d829c6b --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/setup.py @@ -0,0 +1,99 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = 'google-cloud-kms' + + +description = "Google Cloud Kms API client library" + +version = None + +with open(os.path.join(package_root, 'google/cloud/kms/gapic_version.py')) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert (len(version_candidates) == 1) + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", + "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", +] +extras = { +} +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + extras_require=extras, + include_package_data=True, + zip_safe=False, +) diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.10.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.11.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.13.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.13.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.7.txt new file mode 100644 index 000000000000..a81fb6bcd05c --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.7.txt @@ -0,0 +1,11 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.20.2 +grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.8.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ad3f0fa58e2d --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.9.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/__init__.py b/owl-bot-staging/google-cloud-kms/v1/tests/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/tests/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/tests/unit/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/__init__.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/__init__.py new file mode 100644 index 000000000000..7b3de3117f38 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/__init__.py @@ -0,0 +1,16 @@ + +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey.py new file mode 100644 index 000000000000..f1c8bcb11842 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey.py @@ -0,0 +1,5012 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import future +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import operation +from google.api_core import operation_async # type: ignore +from google.api_core import operations_v1 +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.kms_v1.services.autokey import AutokeyAsyncClient +from google.cloud.kms_v1.services.autokey import AutokeyClient +from google.cloud.kms_v1.services.autokey import pagers +from google.cloud.kms_v1.services.autokey import transports +from google.cloud.kms_v1.types import autokey +from google.cloud.location import locations_pb2 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +import google.auth + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AutokeyClient._get_default_mtls_endpoint(None) is None + assert AutokeyClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AutokeyClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AutokeyClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AutokeyClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AutokeyClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AutokeyClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AutokeyClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AutokeyClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AutokeyClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert AutokeyClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AutokeyClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AutokeyClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AutokeyClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert AutokeyClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert AutokeyClient._get_client_cert_source(None, False) is None + assert AutokeyClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AutokeyClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert AutokeyClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AutokeyClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AutokeyClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyClient)) +@mock.patch.object(AutokeyAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AutokeyClient._DEFAULT_UNIVERSE + default_endpoint = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AutokeyClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AutokeyClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutokeyClient.DEFAULT_MTLS_ENDPOINT + assert AutokeyClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AutokeyClient._get_api_endpoint(None, None, default_universe, "always") == AutokeyClient.DEFAULT_MTLS_ENDPOINT + assert AutokeyClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutokeyClient.DEFAULT_MTLS_ENDPOINT + assert AutokeyClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AutokeyClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AutokeyClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert AutokeyClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AutokeyClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AutokeyClient._get_universe_domain(None, None) == AutokeyClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AutokeyClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AutokeyClient, "grpc"), + (AutokeyAsyncClient, "grpc_asyncio"), + (AutokeyClient, "rest"), +]) +def test_autokey_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 == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudkms.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AutokeyGrpcTransport, "grpc"), + (transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AutokeyRestTransport, "rest"), +]) +def test_autokey_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", [ + (AutokeyClient, "grpc"), + (AutokeyAsyncClient, "grpc_asyncio"), + (AutokeyClient, "rest"), +]) +def test_autokey_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 == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudkms.googleapis.com' + ) + + +def test_autokey_client_get_transport_class(): + transport = AutokeyClient.get_transport_class() + available_transports = [ + transports.AutokeyGrpcTransport, + transports.AutokeyRestTransport, + ] + assert transport in available_transports + + transport = AutokeyClient.get_transport_class("grpc") + assert transport == transports.AutokeyGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AutokeyClient, transports.AutokeyGrpcTransport, "grpc"), + (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio"), + (AutokeyClient, transports.AutokeyRestTransport, "rest"), +]) +@mock.patch.object(AutokeyClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyClient)) +@mock.patch.object(AutokeyAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAsyncClient)) +def test_autokey_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(AutokeyClient, '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(AutokeyClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AutokeyClient, transports.AutokeyGrpcTransport, "grpc", "true"), + (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AutokeyClient, transports.AutokeyGrpcTransport, "grpc", "false"), + (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AutokeyClient, transports.AutokeyRestTransport, "rest", "true"), + (AutokeyClient, transports.AutokeyRestTransport, "rest", "false"), +]) +@mock.patch.object(AutokeyClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyClient)) +@mock.patch.object(AutokeyAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_autokey_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + AutokeyClient, AutokeyAsyncClient +]) +@mock.patch.object(AutokeyClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutokeyClient)) +@mock.patch.object(AutokeyAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutokeyAsyncClient)) +def test_autokey_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + AutokeyClient, AutokeyAsyncClient +]) +@mock.patch.object(AutokeyClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyClient)) +@mock.patch.object(AutokeyAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAsyncClient)) +def test_autokey_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AutokeyClient._DEFAULT_UNIVERSE + default_endpoint = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AutokeyClient, transports.AutokeyGrpcTransport, "grpc"), + (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio"), + (AutokeyClient, transports.AutokeyRestTransport, "rest"), +]) +def test_autokey_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (AutokeyClient, transports.AutokeyGrpcTransport, "grpc", grpc_helpers), + (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AutokeyClient, transports.AutokeyRestTransport, "rest", None), +]) +def test_autokey_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_autokey_client_client_options_from_dict(): + with mock.patch('google.cloud.kms_v1.services.autokey.transports.AutokeyGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AutokeyClient( + 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", [ + (AutokeyClient, transports.AutokeyGrpcTransport, "grpc", grpc_helpers), + (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_autokey_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + scopes=None, + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + autokey.CreateKeyHandleRequest, + dict, +]) +def test_create_key_handle(request_type, transport: str = 'grpc'): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_handle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name='operations/spam') + response = client.create_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autokey.CreateKeyHandleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_key_handle_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autokey.CreateKeyHandleRequest( + parent='parent_value', + key_handle_id='key_handle_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_handle), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_key_handle(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == autokey.CreateKeyHandleRequest( + parent='parent_value', + key_handle_id='key_handle_id_value', + ) + +def test_create_key_handle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_key_handle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_key_handle] = mock_rpc + request = {} + client.create_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_key_handle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_key_handle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_key_handle in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_key_handle] = mock_rpc + + request = {} + await client.create_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_key_handle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_key_handle_async(transport: str = 'grpc_asyncio', request_type=autokey.CreateKeyHandleRequest): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_handle), + '__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_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autokey.CreateKeyHandleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_key_handle_async_from_dict(): + await test_create_key_handle_async(request_type=dict) + +def test_create_key_handle_field_headers(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey.CreateKeyHandleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_handle), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_key_handle_field_headers_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey.CreateKeyHandleRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_handle), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) + await client.create_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_key_handle_flattened(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_handle), + '__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_key_handle( + parent='parent_value', + key_handle=autokey.KeyHandle(name='name_value'), + key_handle_id='key_handle_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].key_handle + mock_val = autokey.KeyHandle(name='name_value') + assert arg == mock_val + arg = args[0].key_handle_id + mock_val = 'key_handle_id_value' + assert arg == mock_val + + +def test_create_key_handle_flattened_error(): + client = AutokeyClient( + credentials=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_key_handle( + autokey.CreateKeyHandleRequest(), + parent='parent_value', + key_handle=autokey.KeyHandle(name='name_value'), + key_handle_id='key_handle_id_value', + ) + +@pytest.mark.asyncio +async def test_create_key_handle_flattened_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_handle), + '__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_key_handle( + parent='parent_value', + key_handle=autokey.KeyHandle(name='name_value'), + key_handle_id='key_handle_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = 'parent_value' + assert arg == mock_val + arg = args[0].key_handle + mock_val = autokey.KeyHandle(name='name_value') + assert arg == mock_val + arg = args[0].key_handle_id + mock_val = 'key_handle_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_key_handle_flattened_error_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_key_handle( + autokey.CreateKeyHandleRequest(), + parent='parent_value', + key_handle=autokey.KeyHandle(name='name_value'), + key_handle_id='key_handle_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + autokey.GetKeyHandleRequest, + dict, +]) +def test_get_key_handle(request_type, transport: str = 'grpc'): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_handle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey.KeyHandle( + name='name_value', + kms_key='kms_key_value', + resource_type_selector='resource_type_selector_value', + ) + response = client.get_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autokey.GetKeyHandleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey.KeyHandle) + assert response.name == 'name_value' + assert response.kms_key == 'kms_key_value' + assert response.resource_type_selector == 'resource_type_selector_value' + + +def test_get_key_handle_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autokey.GetKeyHandleRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_handle), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_key_handle(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == autokey.GetKeyHandleRequest( + name='name_value', + ) + +def test_get_key_handle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_key_handle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_key_handle] = mock_rpc + request = {} + client.get_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_key_handle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_key_handle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_key_handle in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_key_handle] = mock_rpc + + request = {} + await client.get_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_key_handle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_key_handle_async(transport: str = 'grpc_asyncio', request_type=autokey.GetKeyHandleRequest): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_handle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autokey.KeyHandle( + name='name_value', + kms_key='kms_key_value', + resource_type_selector='resource_type_selector_value', + )) + response = await client.get_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autokey.GetKeyHandleRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey.KeyHandle) + assert response.name == 'name_value' + assert response.kms_key == 'kms_key_value' + assert response.resource_type_selector == 'resource_type_selector_value' + + +@pytest.mark.asyncio +async def test_get_key_handle_async_from_dict(): + await test_get_key_handle_async(request_type=dict) + +def test_get_key_handle_field_headers(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey.GetKeyHandleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_handle), + '__call__') as call: + call.return_value = autokey.KeyHandle() + client.get_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_key_handle_field_headers_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey.GetKeyHandleRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_handle), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.KeyHandle()) + await client.get_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_key_handle_flattened(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_handle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey.KeyHandle() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_key_handle( + 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_key_handle_flattened_error(): + client = AutokeyClient( + credentials=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_key_handle( + autokey.GetKeyHandleRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_key_handle_flattened_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_handle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey.KeyHandle() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.KeyHandle()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_key_handle( + 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_key_handle_flattened_error_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_key_handle( + autokey.GetKeyHandleRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + autokey.ListKeyHandlesRequest, + dict, +]) +def test_list_key_handles(request_type, transport: str = 'grpc'): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_handles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey.ListKeyHandlesResponse( + next_page_token='next_page_token_value', + ) + response = client.list_key_handles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autokey.ListKeyHandlesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyHandlesPager) + assert response.next_page_token == 'next_page_token_value' + + +def test_list_key_handles_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autokey.ListKeyHandlesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_handles), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_key_handles(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == autokey.ListKeyHandlesRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + ) + +def test_list_key_handles_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_key_handles in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_key_handles] = mock_rpc + request = {} + client.list_key_handles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_key_handles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_key_handles_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_key_handles in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_key_handles] = mock_rpc + + request = {} + await client.list_key_handles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_key_handles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_key_handles_async(transport: str = 'grpc_asyncio', request_type=autokey.ListKeyHandlesRequest): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_handles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autokey.ListKeyHandlesResponse( + next_page_token='next_page_token_value', + )) + response = await client.list_key_handles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autokey.ListKeyHandlesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyHandlesAsyncPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.asyncio +async def test_list_key_handles_async_from_dict(): + await test_list_key_handles_async(request_type=dict) + +def test_list_key_handles_field_headers(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey.ListKeyHandlesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_handles), + '__call__') as call: + call.return_value = autokey.ListKeyHandlesResponse() + client.list_key_handles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_key_handles_field_headers_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey.ListKeyHandlesRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_handles), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.ListKeyHandlesResponse()) + await client.list_key_handles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_key_handles_flattened(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_handles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey.ListKeyHandlesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_key_handles( + 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_key_handles_flattened_error(): + client = AutokeyClient( + credentials=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_key_handles( + autokey.ListKeyHandlesRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_key_handles_flattened_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_handles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey.ListKeyHandlesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.ListKeyHandlesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_key_handles( + 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_key_handles_flattened_error_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_key_handles( + autokey.ListKeyHandlesRequest(), + parent='parent_value', + ) + + +def test_list_key_handles_pager(transport_name: str = "grpc"): + client = AutokeyClient( + 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_key_handles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + autokey.KeyHandle(), + autokey.KeyHandle(), + ], + next_page_token='abc', + ), + autokey.ListKeyHandlesResponse( + key_handles=[], + next_page_token='def', + ), + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + ], + next_page_token='ghi', + ), + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + autokey.KeyHandle(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_key_handles(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, autokey.KeyHandle) + for i in results) +def test_list_key_handles_pages(transport_name: str = "grpc"): + client = AutokeyClient( + 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_key_handles), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + autokey.KeyHandle(), + autokey.KeyHandle(), + ], + next_page_token='abc', + ), + autokey.ListKeyHandlesResponse( + key_handles=[], + next_page_token='def', + ), + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + ], + next_page_token='ghi', + ), + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + autokey.KeyHandle(), + ], + ), + RuntimeError, + ) + pages = list(client.list_key_handles(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_key_handles_async_pager(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_handles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + autokey.KeyHandle(), + autokey.KeyHandle(), + ], + next_page_token='abc', + ), + autokey.ListKeyHandlesResponse( + key_handles=[], + next_page_token='def', + ), + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + ], + next_page_token='ghi', + ), + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + autokey.KeyHandle(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_key_handles(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, autokey.KeyHandle) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_key_handles_async_pages(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_handles), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + autokey.KeyHandle(), + autokey.KeyHandle(), + ], + next_page_token='abc', + ), + autokey.ListKeyHandlesResponse( + key_handles=[], + next_page_token='def', + ), + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + ], + next_page_token='ghi', + ), + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + autokey.KeyHandle(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_key_handles(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_create_key_handle_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_key_handle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_key_handle] = mock_rpc + + request = {} + client.create_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_key_handle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_key_handle_rest_required_fields(request_type=autokey.CreateKeyHandleRequest): + transport_class = transports.AutokeyRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_key_handle._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_key_handle._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("key_handle_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_key_handle(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_key_handle_rest_unset_required_fields(): + transport = transports.AutokeyRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_key_handle._get_unset_required_fields({}) + assert set(unset_fields) == (set(("keyHandleId", )) & set(("parent", "keyHandle", ))) + + +def test_create_key_handle_rest_flattened(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.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', + key_handle=autokey.KeyHandle(name='name_value'), + key_handle_id='key_handle_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_key_handle(**mock_args) + + # Establish that the underlying call 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/*}/keyHandles" % client.transport._host, args[1]) + + +def test_create_key_handle_rest_flattened_error(transport: str = 'rest'): + client = AutokeyClient( + credentials=ga_credentials.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_key_handle( + autokey.CreateKeyHandleRequest(), + parent='parent_value', + key_handle=autokey.KeyHandle(name='name_value'), + key_handle_id='key_handle_id_value', + ) + + +def test_get_key_handle_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_key_handle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_key_handle] = mock_rpc + + request = {} + client.get_key_handle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_key_handle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_key_handle_rest_required_fields(request_type=autokey.GetKeyHandleRequest): + transport_class = transports.AutokeyRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_key_handle._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_key_handle._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autokey.KeyHandle() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autokey.KeyHandle.pb(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_key_handle(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_key_handle_rest_unset_required_fields(): + transport = transports.AutokeyRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_key_handle._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_key_handle_rest_flattened(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = autokey.KeyHandle() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyHandles/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = autokey.KeyHandle.pb(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_key_handle(**mock_args) + + # Establish that the underlying call 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/*/keyHandles/*}" % client.transport._host, args[1]) + + +def test_get_key_handle_rest_flattened_error(transport: str = 'rest'): + client = AutokeyClient( + credentials=ga_credentials.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_key_handle( + autokey.GetKeyHandleRequest(), + name='name_value', + ) + + +def test_list_key_handles_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_key_handles in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_key_handles] = mock_rpc + + request = {} + client.list_key_handles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_key_handles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_key_handles_rest_required_fields(request_type=autokey.ListKeyHandlesRequest): + transport_class = transports.AutokeyRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_key_handles._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_key_handles._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autokey.ListKeyHandlesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autokey.ListKeyHandlesResponse.pb(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_key_handles(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_key_handles_rest_unset_required_fields(): + transport = transports.AutokeyRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_key_handles._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_key_handles_rest_flattened(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = autokey.ListKeyHandlesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = autokey.ListKeyHandlesResponse.pb(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_key_handles(**mock_args) + + # Establish that the underlying call 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/*}/keyHandles" % client.transport._host, args[1]) + + +def test_list_key_handles_rest_flattened_error(transport: str = 'rest'): + client = AutokeyClient( + credentials=ga_credentials.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_key_handles( + autokey.ListKeyHandlesRequest(), + parent='parent_value', + ) + + +def test_list_key_handles_rest_pager(transport: str = 'rest'): + client = AutokeyClient( + 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 = ( + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + autokey.KeyHandle(), + autokey.KeyHandle(), + ], + next_page_token='abc', + ), + autokey.ListKeyHandlesResponse( + key_handles=[], + next_page_token='def', + ), + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + ], + next_page_token='ghi', + ), + autokey.ListKeyHandlesResponse( + key_handles=[ + autokey.KeyHandle(), + autokey.KeyHandle(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(autokey.ListKeyHandlesResponse.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_key_handles(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, autokey.KeyHandle) + for i in results) + + pages = list(client.list_key_handles(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.AutokeyGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AutokeyGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutokeyClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AutokeyGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AutokeyClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AutokeyClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AutokeyGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutokeyClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutokeyGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AutokeyClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutokeyGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AutokeyGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AutokeyGrpcTransport, + transports.AutokeyGrpcAsyncIOTransport, + transports.AutokeyRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = AutokeyClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_key_handle_empty_call_grpc(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_key_handle), + '__call__') as call: + call.return_value = operations_pb2.Operation(name='operations/op') + client.create_key_handle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey.CreateKeyHandleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_key_handle_empty_call_grpc(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_key_handle), + '__call__') as call: + call.return_value = autokey.KeyHandle() + client.get_key_handle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey.GetKeyHandleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_key_handles_empty_call_grpc(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_key_handles), + '__call__') as call: + call.return_value = autokey.ListKeyHandlesResponse() + client.list_key_handles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey.ListKeyHandlesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AutokeyAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_key_handle_empty_call_grpc_asyncio(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_key_handle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name='operations/spam') + ) + await client.create_key_handle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey.CreateKeyHandleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_key_handle_empty_call_grpc_asyncio(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_key_handle), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.KeyHandle( + name='name_value', + kms_key='kms_key_value', + resource_type_selector='resource_type_selector_value', + )) + await client.get_key_handle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey.GetKeyHandleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_key_handles_empty_call_grpc_asyncio(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_key_handles), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.ListKeyHandlesResponse( + next_page_token='next_page_token_value', + )) + await client.list_key_handles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey.ListKeyHandlesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AutokeyClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_create_key_handle_rest_bad_request(request_type=autokey.CreateKeyHandleRequest): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_key_handle(request) + + +@pytest.mark.parametrize("request_type", [ + autokey.CreateKeyHandleRequest, + dict, +]) +def test_create_key_handle_rest_call_success(request_type): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["key_handle"] = {'name': 'name_value', 'kms_key': 'kms_key_value', 'resource_type_selector': 'resource_type_selector_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = autokey.CreateKeyHandleRequest.meta.fields["key_handle"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["key_handle"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["key_handle"][field])): + del request_init["key_handle"][field][i][subfield] + else: + del request_init["key_handle"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name='operations/spam') + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_key_handle(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_key_handle_rest_interceptors(null_interceptor): + transport = transports.AutokeyRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutokeyRestInterceptor(), + ) + client = AutokeyClient(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.AutokeyRestInterceptor, "post_create_key_handle") as post, \ + mock.patch.object(transports.AutokeyRestInterceptor, "pre_create_key_handle") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = autokey.CreateKeyHandleRequest.pb(autokey.CreateKeyHandleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = autokey.CreateKeyHandleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.create_key_handle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_key_handle_rest_bad_request(request_type=autokey.GetKeyHandleRequest): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyHandles/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_key_handle(request) + + +@pytest.mark.parametrize("request_type", [ + autokey.GetKeyHandleRequest, + dict, +]) +def test_get_key_handle_rest_call_success(request_type): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyHandles/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = autokey.KeyHandle( + name='name_value', + kms_key='kms_key_value', + resource_type_selector='resource_type_selector_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autokey.KeyHandle.pb(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_key_handle(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey.KeyHandle) + assert response.name == 'name_value' + assert response.kms_key == 'kms_key_value' + assert response.resource_type_selector == 'resource_type_selector_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_key_handle_rest_interceptors(null_interceptor): + transport = transports.AutokeyRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutokeyRestInterceptor(), + ) + client = AutokeyClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AutokeyRestInterceptor, "post_get_key_handle") as post, \ + mock.patch.object(transports.AutokeyRestInterceptor, "pre_get_key_handle") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = autokey.GetKeyHandleRequest.pb(autokey.GetKeyHandleRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = autokey.KeyHandle.to_json(autokey.KeyHandle()) + req.return_value.content = return_value + + request = autokey.GetKeyHandleRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autokey.KeyHandle() + + client.get_key_handle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_key_handles_rest_bad_request(request_type=autokey.ListKeyHandlesRequest): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_key_handles(request) + + +@pytest.mark.parametrize("request_type", [ + autokey.ListKeyHandlesRequest, + dict, +]) +def test_list_key_handles_rest_call_success(request_type): + client = AutokeyClient( + 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 = autokey.ListKeyHandlesResponse( + next_page_token='next_page_token_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autokey.ListKeyHandlesResponse.pb(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_key_handles(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyHandlesPager) + assert response.next_page_token == 'next_page_token_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_key_handles_rest_interceptors(null_interceptor): + transport = transports.AutokeyRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutokeyRestInterceptor(), + ) + client = AutokeyClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AutokeyRestInterceptor, "post_list_key_handles") as post, \ + mock.patch.object(transports.AutokeyRestInterceptor, "pre_list_key_handles") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = autokey.ListKeyHandlesRequest.pb(autokey.ListKeyHandlesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = autokey.ListKeyHandlesResponse.to_json(autokey.ListKeyHandlesResponse()) + req.return_value.content = return_value + + request = autokey.ListKeyHandlesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autokey.ListKeyHandlesResponse() + + client.list_key_handles(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_initialize_client_w_rest(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_key_handle_empty_call_rest(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_key_handle), + '__call__') as call: + client.create_key_handle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey.CreateKeyHandleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_key_handle_empty_call_rest(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_key_handle), + '__call__') as call: + client.get_key_handle(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey.GetKeyHandleRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_key_handles_empty_call_rest(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_key_handles), + '__call__') as call: + client.list_key_handles(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey.ListKeyHandlesRequest() + + assert args[0] == request_msg + + +def test_autokey_rest_lro_client(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have an api-core operations client. + assert isinstance( + transport.operations_client, +operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AutokeyGrpcTransport, + ) + +def test_autokey_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AutokeyTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_autokey_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.kms_v1.services.autokey.transports.AutokeyTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AutokeyTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'create_key_handle', + 'get_key_handle', + 'list_key_handles', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + ) + 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_autokey_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.kms_v1.services.autokey.transports.AutokeyTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutokeyTransport( + 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', + 'https://www.googleapis.com/auth/cloudkms', +), + quota_project_id="octopus", + ) + + +def test_autokey_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.kms_v1.services.autokey.transports.AutokeyTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutokeyTransport() + adc.assert_called_once() + + +def test_autokey_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) + AutokeyClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutokeyGrpcTransport, + transports.AutokeyGrpcAsyncIOTransport, + ], +) +def test_autokey_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', 'https://www.googleapis.com/auth/cloudkms',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutokeyGrpcTransport, + transports.AutokeyGrpcAsyncIOTransport, + transports.AutokeyRestTransport, + ], +) +def test_autokey_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.AutokeyGrpcTransport, grpc_helpers), + (transports.AutokeyGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_autokey_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( + "cloudkms.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + scopes=["1", "2"], + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AutokeyGrpcTransport, transports.AutokeyGrpcAsyncIOTransport]) +def test_autokey_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_autokey_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.AutokeyRestTransport ( + 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_autokey_host_no_port(transport_name): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudkms.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_autokey_host_with_port(transport_name): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudkms.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudkms.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_autokey_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AutokeyClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AutokeyClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_key_handle._session + session2 = client2.transport.create_key_handle._session + assert session1 != session2 + session1 = client1.transport.get_key_handle._session + session2 = client2.transport.get_key_handle._session + assert session1 != session2 + session1 = client1.transport.list_key_handles._session + session2 = client2.transport.list_key_handles._session + assert session1 != session2 +def test_autokey_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutokeyGrpcTransport( + 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_autokey_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutokeyGrpcAsyncIOTransport( + 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.AutokeyGrpcTransport, transports.AutokeyGrpcAsyncIOTransport]) +def test_autokey_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.AutokeyGrpcTransport, transports.AutokeyGrpcAsyncIOTransport]) +def test_autokey_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_autokey_grpc_lro_client(): + client = AutokeyClient( + 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_autokey_grpc_lro_async_client(): + client = AutokeyAsyncClient( + 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_crypto_key_path(): + project = "squid" + location = "clam" + key_ring = "whelk" + crypto_key = "octopus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + actual = AutokeyClient.crypto_key_path(project, location, key_ring, crypto_key) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "key_ring": "cuttlefish", + "crypto_key": "mussel", + } + path = AutokeyClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyClient.parse_crypto_key_path(path) + assert expected == actual + +def test_key_handle_path(): + project = "winkle" + location = "nautilus" + key_handle = "scallop" + expected = "projects/{project}/locations/{location}/keyHandles/{key_handle}".format(project=project, location=location, key_handle=key_handle, ) + actual = AutokeyClient.key_handle_path(project, location, key_handle) + assert expected == actual + + +def test_parse_key_handle_path(): + expected = { + "project": "abalone", + "location": "squid", + "key_handle": "clam", + } + path = AutokeyClient.key_handle_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyClient.parse_key_handle_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AutokeyClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = AutokeyClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = AutokeyClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = AutokeyClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AutokeyClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = AutokeyClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = AutokeyClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = AutokeyClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AutokeyClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = AutokeyClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyClient.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.AutokeyTransport, '_prep_wrapped_messages') as prep: + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AutokeyTransport, '_prep_wrapped_messages') as prep: + transport_class = AutokeyClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_get_operation(transport: str = "grpc"): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = AutokeyClient( + 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 = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = AutokeyAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = AutokeyClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = AutokeyClient( + 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", [ + (AutokeyClient, transports.AutokeyGrpcTransport), + (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey_admin.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey_admin.py new file mode 100644 index 000000000000..64ab5f6a03e9 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey_admin.py @@ -0,0 +1,4652 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.kms_v1.services.autokey_admin import AutokeyAdminAsyncClient +from google.cloud.kms_v1.services.autokey_admin import AutokeyAdminClient +from google.cloud.kms_v1.services.autokey_admin import transports +from google.cloud.kms_v1.types import autokey_admin +from google.cloud.location import locations_pb2 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert AutokeyAdminClient._get_default_mtls_endpoint(None) is None + assert AutokeyAdminClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert AutokeyAdminClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert AutokeyAdminClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert AutokeyAdminClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert AutokeyAdminClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert AutokeyAdminClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert AutokeyAdminClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert AutokeyAdminClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + AutokeyAdminClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert AutokeyAdminClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert AutokeyAdminClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert AutokeyAdminClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + AutokeyAdminClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert AutokeyAdminClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert AutokeyAdminClient._get_client_cert_source(None, False) is None + assert AutokeyAdminClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert AutokeyAdminClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert AutokeyAdminClient._get_client_cert_source(None, True) is mock_default_cert_source + assert AutokeyAdminClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(AutokeyAdminClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminClient)) +@mock.patch.object(AutokeyAdminAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = AutokeyAdminClient._DEFAULT_UNIVERSE + default_endpoint = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert AutokeyAdminClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert AutokeyAdminClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutokeyAdminClient.DEFAULT_MTLS_ENDPOINT + assert AutokeyAdminClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert AutokeyAdminClient._get_api_endpoint(None, None, default_universe, "always") == AutokeyAdminClient.DEFAULT_MTLS_ENDPOINT + assert AutokeyAdminClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutokeyAdminClient.DEFAULT_MTLS_ENDPOINT + assert AutokeyAdminClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert AutokeyAdminClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + AutokeyAdminClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert AutokeyAdminClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert AutokeyAdminClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert AutokeyAdminClient._get_universe_domain(None, None) == AutokeyAdminClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + AutokeyAdminClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (AutokeyAdminClient, "grpc"), + (AutokeyAdminAsyncClient, "grpc_asyncio"), + (AutokeyAdminClient, "rest"), +]) +def test_autokey_admin_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 == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudkms.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.AutokeyAdminGrpcTransport, "grpc"), + (transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.AutokeyAdminRestTransport, "rest"), +]) +def test_autokey_admin_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", [ + (AutokeyAdminClient, "grpc"), + (AutokeyAdminAsyncClient, "grpc_asyncio"), + (AutokeyAdminClient, "rest"), +]) +def test_autokey_admin_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 == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudkms.googleapis.com' + ) + + +def test_autokey_admin_client_get_transport_class(): + transport = AutokeyAdminClient.get_transport_class() + available_transports = [ + transports.AutokeyAdminGrpcTransport, + transports.AutokeyAdminRestTransport, + ] + assert transport in available_transports + + transport = AutokeyAdminClient.get_transport_class("grpc") + assert transport == transports.AutokeyAdminGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc"), + (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (AutokeyAdminClient, transports.AutokeyAdminRestTransport, "rest"), +]) +@mock.patch.object(AutokeyAdminClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminClient)) +@mock.patch.object(AutokeyAdminAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminAsyncClient)) +def test_autokey_admin_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(AutokeyAdminClient, '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(AutokeyAdminClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc", "true"), + (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc", "false"), + (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (AutokeyAdminClient, transports.AutokeyAdminRestTransport, "rest", "true"), + (AutokeyAdminClient, transports.AutokeyAdminRestTransport, "rest", "false"), +]) +@mock.patch.object(AutokeyAdminClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminClient)) +@mock.patch.object(AutokeyAdminAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_autokey_admin_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + AutokeyAdminClient, AutokeyAdminAsyncClient +]) +@mock.patch.object(AutokeyAdminClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutokeyAdminClient)) +@mock.patch.object(AutokeyAdminAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutokeyAdminAsyncClient)) +def test_autokey_admin_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + AutokeyAdminClient, AutokeyAdminAsyncClient +]) +@mock.patch.object(AutokeyAdminClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminClient)) +@mock.patch.object(AutokeyAdminAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminAsyncClient)) +def test_autokey_admin_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = AutokeyAdminClient._DEFAULT_UNIVERSE + default_endpoint = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc"), + (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio"), + (AutokeyAdminClient, transports.AutokeyAdminRestTransport, "rest"), +]) +def test_autokey_admin_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc", grpc_helpers), + (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (AutokeyAdminClient, transports.AutokeyAdminRestTransport, "rest", None), +]) +def test_autokey_admin_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_autokey_admin_client_client_options_from_dict(): + with mock.patch('google.cloud.kms_v1.services.autokey_admin.transports.AutokeyAdminGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = AutokeyAdminClient( + 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", [ + (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc", grpc_helpers), + (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_autokey_admin_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + scopes=None, + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + autokey_admin.UpdateAutokeyConfigRequest, + dict, +]) +def test_update_autokey_config(request_type, transport: str = 'grpc'): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey_admin.AutokeyConfig( + name='name_value', + key_project='key_project_value', + state=autokey_admin.AutokeyConfig.State.ACTIVE, + ) + response = client.update_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autokey_admin.UpdateAutokeyConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey_admin.AutokeyConfig) + assert response.name == 'name_value' + assert response.key_project == 'key_project_value' + assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE + + +def test_update_autokey_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autokey_admin.UpdateAutokeyConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autokey_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_autokey_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == autokey_admin.UpdateAutokeyConfigRequest( + ) + +def test_update_autokey_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_autokey_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_autokey_config] = mock_rpc + request = {} + client.update_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_autokey_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_autokey_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_autokey_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_autokey_config] = mock_rpc + + request = {} + await client.update_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_autokey_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_autokey_config_async(transport: str = 'grpc_asyncio', request_type=autokey_admin.UpdateAutokeyConfigRequest): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig( + name='name_value', + key_project='key_project_value', + state=autokey_admin.AutokeyConfig.State.ACTIVE, + )) + response = await client.update_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autokey_admin.UpdateAutokeyConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey_admin.AutokeyConfig) + assert response.name == 'name_value' + assert response.key_project == 'key_project_value' + assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE + + +@pytest.mark.asyncio +async def test_update_autokey_config_async_from_dict(): + await test_update_autokey_config_async(request_type=dict) + +def test_update_autokey_config_field_headers(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey_admin.UpdateAutokeyConfigRequest() + + request.autokey_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autokey_config), + '__call__') as call: + call.return_value = autokey_admin.AutokeyConfig() + client.update_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'autokey_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_autokey_config_field_headers_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey_admin.UpdateAutokeyConfigRequest() + + request.autokey_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autokey_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig()) + await client.update_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'autokey_config.name=name_value', + ) in kw['metadata'] + + +def test_update_autokey_config_flattened(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey_admin.AutokeyConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_autokey_config( + autokey_config=autokey_admin.AutokeyConfig(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].autokey_config + mock_val = autokey_admin.AutokeyConfig(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_autokey_config_flattened_error(): + client = AutokeyAdminClient( + credentials=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_autokey_config( + autokey_admin.UpdateAutokeyConfigRequest(), + autokey_config=autokey_admin.AutokeyConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_autokey_config_flattened_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey_admin.AutokeyConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_autokey_config( + autokey_config=autokey_admin.AutokeyConfig(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].autokey_config + mock_val = autokey_admin.AutokeyConfig(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_autokey_config_flattened_error_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_autokey_config( + autokey_admin.UpdateAutokeyConfigRequest(), + autokey_config=autokey_admin.AutokeyConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + autokey_admin.GetAutokeyConfigRequest, + dict, +]) +def test_get_autokey_config(request_type, transport: str = 'grpc'): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey_admin.AutokeyConfig( + name='name_value', + key_project='key_project_value', + state=autokey_admin.AutokeyConfig.State.ACTIVE, + ) + response = client.get_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autokey_admin.GetAutokeyConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey_admin.AutokeyConfig) + assert response.name == 'name_value' + assert response.key_project == 'key_project_value' + assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE + + +def test_get_autokey_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autokey_admin.GetAutokeyConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autokey_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_autokey_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == autokey_admin.GetAutokeyConfigRequest( + name='name_value', + ) + +def test_get_autokey_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_autokey_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_autokey_config] = mock_rpc + request = {} + client.get_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_autokey_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_autokey_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_autokey_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_autokey_config] = mock_rpc + + request = {} + await client.get_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_autokey_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_autokey_config_async(transport: str = 'grpc_asyncio', request_type=autokey_admin.GetAutokeyConfigRequest): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig( + name='name_value', + key_project='key_project_value', + state=autokey_admin.AutokeyConfig.State.ACTIVE, + )) + response = await client.get_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autokey_admin.GetAutokeyConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey_admin.AutokeyConfig) + assert response.name == 'name_value' + assert response.key_project == 'key_project_value' + assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE + + +@pytest.mark.asyncio +async def test_get_autokey_config_async_from_dict(): + await test_get_autokey_config_async(request_type=dict) + +def test_get_autokey_config_field_headers(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey_admin.GetAutokeyConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autokey_config), + '__call__') as call: + call.return_value = autokey_admin.AutokeyConfig() + client.get_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_autokey_config_field_headers_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey_admin.GetAutokeyConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autokey_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig()) + await client.get_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_autokey_config_flattened(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey_admin.AutokeyConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_autokey_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_autokey_config_flattened_error(): + client = AutokeyAdminClient( + credentials=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_autokey_config( + autokey_admin.GetAutokeyConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_autokey_config_flattened_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey_admin.AutokeyConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_autokey_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_autokey_config_flattened_error_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_autokey_config( + autokey_admin.GetAutokeyConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + autokey_admin.ShowEffectiveAutokeyConfigRequest, + dict, +]) +def test_show_effective_autokey_config(request_type, transport: str = 'grpc'): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.show_effective_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse( + key_project='key_project_value', + ) + response = client.show_effective_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autokey_admin.ShowEffectiveAutokeyConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey_admin.ShowEffectiveAutokeyConfigResponse) + assert response.key_project == 'key_project_value' + + +def test_show_effective_autokey_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = autokey_admin.ShowEffectiveAutokeyConfigRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.show_effective_autokey_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.show_effective_autokey_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == autokey_admin.ShowEffectiveAutokeyConfigRequest( + parent='parent_value', + ) + +def test_show_effective_autokey_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.show_effective_autokey_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.show_effective_autokey_config] = mock_rpc + request = {} + client.show_effective_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.show_effective_autokey_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_show_effective_autokey_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.show_effective_autokey_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.show_effective_autokey_config] = mock_rpc + + request = {} + await client.show_effective_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.show_effective_autokey_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_show_effective_autokey_config_async(transport: str = 'grpc_asyncio', request_type=autokey_admin.ShowEffectiveAutokeyConfigRequest): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.show_effective_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.ShowEffectiveAutokeyConfigResponse( + key_project='key_project_value', + )) + response = await client.show_effective_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autokey_admin.ShowEffectiveAutokeyConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey_admin.ShowEffectiveAutokeyConfigResponse) + assert response.key_project == 'key_project_value' + + +@pytest.mark.asyncio +async def test_show_effective_autokey_config_async_from_dict(): + await test_show_effective_autokey_config_async(request_type=dict) + +def test_show_effective_autokey_config_field_headers(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey_admin.ShowEffectiveAutokeyConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.show_effective_autokey_config), + '__call__') as call: + call.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() + client.show_effective_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_show_effective_autokey_config_field_headers_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = autokey_admin.ShowEffectiveAutokeyConfigRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.show_effective_autokey_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.ShowEffectiveAutokeyConfigResponse()) + await client.show_effective_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_show_effective_autokey_config_flattened(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.show_effective_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.show_effective_autokey_config( + 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_show_effective_autokey_config_flattened_error(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.show_effective_autokey_config( + autokey_admin.ShowEffectiveAutokeyConfigRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_show_effective_autokey_config_flattened_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.show_effective_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.ShowEffectiveAutokeyConfigResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.show_effective_autokey_config( + 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_show_effective_autokey_config_flattened_error_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.show_effective_autokey_config( + autokey_admin.ShowEffectiveAutokeyConfigRequest(), + parent='parent_value', + ) + + +def test_update_autokey_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_autokey_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_autokey_config] = mock_rpc + + request = {} + client.update_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_autokey_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_autokey_config_rest_required_fields(request_type=autokey_admin.UpdateAutokeyConfigRequest): + transport_class = transports.AutokeyAdminRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_autokey_config._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_autokey_config._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 = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autokey_admin.AutokeyConfig() + # 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 + + # Convert return value to protobuf type + return_value = autokey_admin.AutokeyConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_autokey_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_autokey_config_rest_unset_required_fields(): + transport = transports.AutokeyAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_autokey_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("autokeyConfig", "updateMask", ))) + + +def test_update_autokey_config_rest_flattened(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = autokey_admin.AutokeyConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'autokey_config': {'name': 'folders/sample1/autokeyConfig'}} + + # get truthy value for each flattened field + mock_args = dict( + autokey_config=autokey_admin.AutokeyConfig(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 + # Convert return value to protobuf type + return_value = autokey_admin.AutokeyConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_autokey_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{autokey_config.name=folders/*/autokeyConfig}" % client.transport._host, args[1]) + + +def test_update_autokey_config_rest_flattened_error(transport: str = 'rest'): + client = AutokeyAdminClient( + credentials=ga_credentials.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_autokey_config( + autokey_admin.UpdateAutokeyConfigRequest(), + autokey_config=autokey_admin.AutokeyConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_autokey_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_autokey_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_autokey_config] = mock_rpc + + request = {} + client.get_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_autokey_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_autokey_config_rest_required_fields(request_type=autokey_admin.GetAutokeyConfigRequest): + transport_class = transports.AutokeyAdminRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_autokey_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_autokey_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autokey_admin.AutokeyConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autokey_admin.AutokeyConfig.pb(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_autokey_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_autokey_config_rest_unset_required_fields(): + transport = transports.AutokeyAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_autokey_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_autokey_config_rest_flattened(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = autokey_admin.AutokeyConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'folders/sample1/autokeyConfig'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = autokey_admin.AutokeyConfig.pb(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_autokey_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=folders/*/autokeyConfig}" % client.transport._host, args[1]) + + +def test_get_autokey_config_rest_flattened_error(transport: str = 'rest'): + client = AutokeyAdminClient( + credentials=ga_credentials.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_autokey_config( + autokey_admin.GetAutokeyConfigRequest(), + name='name_value', + ) + + +def test_show_effective_autokey_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.show_effective_autokey_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.show_effective_autokey_config] = mock_rpc + + request = {} + client.show_effective_autokey_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.show_effective_autokey_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_show_effective_autokey_config_rest_required_fields(request_type=autokey_admin.ShowEffectiveAutokeyConfigRequest): + transport_class = transports.AutokeyAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).show_effective_autokey_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).show_effective_autokey_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse.pb(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.show_effective_autokey_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_show_effective_autokey_config_rest_unset_required_fields(): + transport = transports.AutokeyAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.show_effective_autokey_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", ))) + + +def test_show_effective_autokey_config_rest_flattened(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse.pb(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.show_effective_autokey_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*}:showEffectiveAutokeyConfig" % client.transport._host, args[1]) + + +def test_show_effective_autokey_config_rest_flattened_error(transport: str = 'rest'): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.show_effective_autokey_config( + autokey_admin.ShowEffectiveAutokeyConfigRequest(), + parent='parent_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.AutokeyAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.AutokeyAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutokeyAdminClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.AutokeyAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AutokeyAdminClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = AutokeyAdminClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.AutokeyAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = AutokeyAdminClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutokeyAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = AutokeyAdminClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.AutokeyAdminGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.AutokeyAdminGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.AutokeyAdminGrpcTransport, + transports.AutokeyAdminGrpcAsyncIOTransport, + transports.AutokeyAdminRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = AutokeyAdminClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_autokey_config_empty_call_grpc(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_autokey_config), + '__call__') as call: + call.return_value = autokey_admin.AutokeyConfig() + client.update_autokey_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey_admin.UpdateAutokeyConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_autokey_config_empty_call_grpc(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_autokey_config), + '__call__') as call: + call.return_value = autokey_admin.AutokeyConfig() + client.get_autokey_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey_admin.GetAutokeyConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_show_effective_autokey_config_empty_call_grpc(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.show_effective_autokey_config), + '__call__') as call: + call.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() + client.show_effective_autokey_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey_admin.ShowEffectiveAutokeyConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = AutokeyAdminAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_autokey_config_empty_call_grpc_asyncio(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig( + name='name_value', + key_project='key_project_value', + state=autokey_admin.AutokeyConfig.State.ACTIVE, + )) + await client.update_autokey_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey_admin.UpdateAutokeyConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_autokey_config_empty_call_grpc_asyncio(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig( + name='name_value', + key_project='key_project_value', + state=autokey_admin.AutokeyConfig.State.ACTIVE, + )) + await client.get_autokey_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey_admin.GetAutokeyConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_show_effective_autokey_config_empty_call_grpc_asyncio(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.show_effective_autokey_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.ShowEffectiveAutokeyConfigResponse( + key_project='key_project_value', + )) + await client.show_effective_autokey_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey_admin.ShowEffectiveAutokeyConfigRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = AutokeyAdminClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_update_autokey_config_rest_bad_request(request_type=autokey_admin.UpdateAutokeyConfigRequest): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'autokey_config': {'name': 'folders/sample1/autokeyConfig'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_autokey_config(request) + + +@pytest.mark.parametrize("request_type", [ + autokey_admin.UpdateAutokeyConfigRequest, + dict, +]) +def test_update_autokey_config_rest_call_success(request_type): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'autokey_config': {'name': 'folders/sample1/autokeyConfig'}} + request_init["autokey_config"] = {'name': 'folders/sample1/autokeyConfig', 'key_project': 'key_project_value', 'state': 1} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = autokey_admin.UpdateAutokeyConfigRequest.meta.fields["autokey_config"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["autokey_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["autokey_config"][field])): + del request_init["autokey_config"][field][i][subfield] + else: + del request_init["autokey_config"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = autokey_admin.AutokeyConfig( + name='name_value', + key_project='key_project_value', + state=autokey_admin.AutokeyConfig.State.ACTIVE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autokey_admin.AutokeyConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_autokey_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey_admin.AutokeyConfig) + assert response.name == 'name_value' + assert response.key_project == 'key_project_value' + assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_autokey_config_rest_interceptors(null_interceptor): + transport = transports.AutokeyAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutokeyAdminRestInterceptor(), + ) + client = AutokeyAdminClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AutokeyAdminRestInterceptor, "post_update_autokey_config") as post, \ + mock.patch.object(transports.AutokeyAdminRestInterceptor, "pre_update_autokey_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = autokey_admin.UpdateAutokeyConfigRequest.pb(autokey_admin.UpdateAutokeyConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = autokey_admin.AutokeyConfig.to_json(autokey_admin.AutokeyConfig()) + req.return_value.content = return_value + + request = autokey_admin.UpdateAutokeyConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autokey_admin.AutokeyConfig() + + client.update_autokey_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_autokey_config_rest_bad_request(request_type=autokey_admin.GetAutokeyConfigRequest): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'folders/sample1/autokeyConfig'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_autokey_config(request) + + +@pytest.mark.parametrize("request_type", [ + autokey_admin.GetAutokeyConfigRequest, + dict, +]) +def test_get_autokey_config_rest_call_success(request_type): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'folders/sample1/autokeyConfig'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = autokey_admin.AutokeyConfig( + name='name_value', + key_project='key_project_value', + state=autokey_admin.AutokeyConfig.State.ACTIVE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autokey_admin.AutokeyConfig.pb(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_autokey_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey_admin.AutokeyConfig) + assert response.name == 'name_value' + assert response.key_project == 'key_project_value' + assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_autokey_config_rest_interceptors(null_interceptor): + transport = transports.AutokeyAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutokeyAdminRestInterceptor(), + ) + client = AutokeyAdminClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AutokeyAdminRestInterceptor, "post_get_autokey_config") as post, \ + mock.patch.object(transports.AutokeyAdminRestInterceptor, "pre_get_autokey_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = autokey_admin.GetAutokeyConfigRequest.pb(autokey_admin.GetAutokeyConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = autokey_admin.AutokeyConfig.to_json(autokey_admin.AutokeyConfig()) + req.return_value.content = return_value + + request = autokey_admin.GetAutokeyConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autokey_admin.AutokeyConfig() + + client.get_autokey_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_show_effective_autokey_config_rest_bad_request(request_type=autokey_admin.ShowEffectiveAutokeyConfigRequest): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.show_effective_autokey_config(request) + + +@pytest.mark.parametrize("request_type", [ + autokey_admin.ShowEffectiveAutokeyConfigRequest, + dict, +]) +def test_show_effective_autokey_config_rest_call_success(request_type): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse( + key_project='key_project_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse.pb(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.show_effective_autokey_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, autokey_admin.ShowEffectiveAutokeyConfigResponse) + assert response.key_project == 'key_project_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_show_effective_autokey_config_rest_interceptors(null_interceptor): + transport = transports.AutokeyAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.AutokeyAdminRestInterceptor(), + ) + client = AutokeyAdminClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.AutokeyAdminRestInterceptor, "post_show_effective_autokey_config") as post, \ + mock.patch.object(transports.AutokeyAdminRestInterceptor, "pre_show_effective_autokey_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = autokey_admin.ShowEffectiveAutokeyConfigRequest.pb(autokey_admin.ShowEffectiveAutokeyConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse.to_json(autokey_admin.ShowEffectiveAutokeyConfigResponse()) + req.return_value.content = return_value + + request = autokey_admin.ShowEffectiveAutokeyConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() + + client.show_effective_autokey_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_initialize_client_w_rest(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_autokey_config_empty_call_rest(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_autokey_config), + '__call__') as call: + client.update_autokey_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey_admin.UpdateAutokeyConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_autokey_config_empty_call_rest(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_autokey_config), + '__call__') as call: + client.get_autokey_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey_admin.GetAutokeyConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_show_effective_autokey_config_empty_call_rest(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.show_effective_autokey_config), + '__call__') as call: + client.show_effective_autokey_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autokey_admin.ShowEffectiveAutokeyConfigRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.AutokeyAdminGrpcTransport, + ) + +def test_autokey_admin_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.AutokeyAdminTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_autokey_admin_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.kms_v1.services.autokey_admin.transports.AutokeyAdminTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.AutokeyAdminTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'update_autokey_config', + 'get_autokey_config', + 'show_effective_autokey_config', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + ) + 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_autokey_admin_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.kms_v1.services.autokey_admin.transports.AutokeyAdminTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutokeyAdminTransport( + 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', + 'https://www.googleapis.com/auth/cloudkms', +), + quota_project_id="octopus", + ) + + +def test_autokey_admin_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.kms_v1.services.autokey_admin.transports.AutokeyAdminTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AutokeyAdminTransport() + adc.assert_called_once() + + +def test_autokey_admin_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) + AutokeyAdminClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutokeyAdminGrpcTransport, + transports.AutokeyAdminGrpcAsyncIOTransport, + ], +) +def test_autokey_admin_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', 'https://www.googleapis.com/auth/cloudkms',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AutokeyAdminGrpcTransport, + transports.AutokeyAdminGrpcAsyncIOTransport, + transports.AutokeyAdminRestTransport, + ], +) +def test_autokey_admin_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.AutokeyAdminGrpcTransport, grpc_helpers), + (transports.AutokeyAdminGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_autokey_admin_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( + "cloudkms.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + scopes=["1", "2"], + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.AutokeyAdminGrpcTransport, transports.AutokeyAdminGrpcAsyncIOTransport]) +def test_autokey_admin_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_autokey_admin_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.AutokeyAdminRestTransport ( + 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_autokey_admin_host_no_port(transport_name): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudkms.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_autokey_admin_host_with_port(transport_name): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudkms.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudkms.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_autokey_admin_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = AutokeyAdminClient( + credentials=creds1, + transport=transport_name, + ) + client2 = AutokeyAdminClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.update_autokey_config._session + session2 = client2.transport.update_autokey_config._session + assert session1 != session2 + session1 = client1.transport.get_autokey_config._session + session2 = client2.transport.get_autokey_config._session + assert session1 != session2 + session1 = client1.transport.show_effective_autokey_config._session + session2 = client2.transport.show_effective_autokey_config._session + assert session1 != session2 +def test_autokey_admin_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutokeyAdminGrpcTransport( + 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_autokey_admin_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.AutokeyAdminGrpcAsyncIOTransport( + 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.AutokeyAdminGrpcTransport, transports.AutokeyAdminGrpcAsyncIOTransport]) +def test_autokey_admin_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.AutokeyAdminGrpcTransport, transports.AutokeyAdminGrpcAsyncIOTransport]) +def test_autokey_admin_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_autokey_config_path(): + folder = "squid" + expected = "folders/{folder}/autokeyConfig".format(folder=folder, ) + actual = AutokeyAdminClient.autokey_config_path(folder) + assert expected == actual + + +def test_parse_autokey_config_path(): + expected = { + "folder": "clam", + } + path = AutokeyAdminClient.autokey_config_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyAdminClient.parse_autokey_config_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "whelk" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = AutokeyAdminClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "octopus", + } + path = AutokeyAdminClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyAdminClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "oyster" + expected = "folders/{folder}".format(folder=folder, ) + actual = AutokeyAdminClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nudibranch", + } + path = AutokeyAdminClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyAdminClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "cuttlefish" + expected = "organizations/{organization}".format(organization=organization, ) + actual = AutokeyAdminClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "mussel", + } + path = AutokeyAdminClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyAdminClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "winkle" + expected = "projects/{project}".format(project=project, ) + actual = AutokeyAdminClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nautilus", + } + path = AutokeyAdminClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyAdminClient.parse_common_project_path(path) + assert expected == actual + +def test_common_location_path(): + project = "scallop" + location = "abalone" + expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) + actual = AutokeyAdminClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "squid", + "location": "clam", + } + path = AutokeyAdminClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = AutokeyAdminClient.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.AutokeyAdminTransport, '_prep_wrapped_messages') as prep: + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.AutokeyAdminTransport, '_prep_wrapped_messages') as prep: + transport_class = AutokeyAdminClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_get_operation(transport: str = "grpc"): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = AutokeyAdminClient( + 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 = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = AutokeyAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = AutokeyAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = AutokeyAdminClient( + 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", [ + (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport), + (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_ekm_service.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_ekm_service.py new file mode 100644 index 000000000000..cae1c5765064 --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_ekm_service.py @@ -0,0 +1,7787 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.kms_v1.services.ekm_service import EkmServiceAsyncClient +from google.cloud.kms_v1.services.ekm_service import EkmServiceClient +from google.cloud.kms_v1.services.ekm_service import pagers +from google.cloud.kms_v1.services.ekm_service import transports +from google.cloud.kms_v1.types import ekm_service +from google.cloud.location import locations_pb2 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert EkmServiceClient._get_default_mtls_endpoint(None) is None + assert EkmServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert EkmServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert EkmServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert EkmServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert EkmServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert EkmServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert EkmServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert EkmServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + EkmServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert EkmServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert EkmServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert EkmServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + EkmServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert EkmServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert EkmServiceClient._get_client_cert_source(None, False) is None + assert EkmServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert EkmServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert EkmServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert EkmServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(EkmServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceClient)) +@mock.patch.object(EkmServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = EkmServiceClient._DEFAULT_UNIVERSE + default_endpoint = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert EkmServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert EkmServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EkmServiceClient.DEFAULT_MTLS_ENDPOINT + assert EkmServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert EkmServiceClient._get_api_endpoint(None, None, default_universe, "always") == EkmServiceClient.DEFAULT_MTLS_ENDPOINT + assert EkmServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EkmServiceClient.DEFAULT_MTLS_ENDPOINT + assert EkmServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert EkmServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + EkmServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert EkmServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert EkmServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert EkmServiceClient._get_universe_domain(None, None) == EkmServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + EkmServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (EkmServiceClient, "grpc"), + (EkmServiceAsyncClient, "grpc_asyncio"), + (EkmServiceClient, "rest"), +]) +def test_ekm_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudkms.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.EkmServiceGrpcTransport, "grpc"), + (transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.EkmServiceRestTransport, "rest"), +]) +def test_ekm_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (EkmServiceClient, "grpc"), + (EkmServiceAsyncClient, "grpc_asyncio"), + (EkmServiceClient, "rest"), +]) +def test_ekm_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudkms.googleapis.com' + ) + + +def test_ekm_service_client_get_transport_class(): + transport = EkmServiceClient.get_transport_class() + available_transports = [ + transports.EkmServiceGrpcTransport, + transports.EkmServiceRestTransport, + ] + assert transport in available_transports + + transport = EkmServiceClient.get_transport_class("grpc") + assert transport == transports.EkmServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (EkmServiceClient, transports.EkmServiceRestTransport, "rest"), +]) +@mock.patch.object(EkmServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceClient)) +@mock.patch.object(EkmServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceAsyncClient)) +def test_ekm_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(EkmServiceClient, '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(EkmServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "true"), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "false"), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (EkmServiceClient, transports.EkmServiceRestTransport, "rest", "true"), + (EkmServiceClient, transports.EkmServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(EkmServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceClient)) +@mock.patch.object(EkmServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_ekm_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + EkmServiceClient, EkmServiceAsyncClient +]) +@mock.patch.object(EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient)) +@mock.patch.object(EkmServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceAsyncClient)) +def test_ekm_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + EkmServiceClient, EkmServiceAsyncClient +]) +@mock.patch.object(EkmServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceClient)) +@mock.patch.object(EkmServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceAsyncClient)) +def test_ekm_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = EkmServiceClient._DEFAULT_UNIVERSE + default_endpoint = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (EkmServiceClient, transports.EkmServiceRestTransport, "rest"), +]) +def test_ekm_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (EkmServiceClient, transports.EkmServiceRestTransport, "rest", None), +]) +def test_ekm_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_ekm_service_client_client_options_from_dict(): + with mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = EkmServiceClient( + 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", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_ekm_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + scopes=None, + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.ListEkmConnectionsRequest, + dict, +]) +def test_list_ekm_connections(request_type, transport: str = 'grpc'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ekm_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.ListEkmConnectionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ekm_service.ListEkmConnectionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEkmConnectionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_ekm_connections_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = ekm_service.ListEkmConnectionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_ekm_connections(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.ListEkmConnectionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_ekm_connections_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_ekm_connections in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_ekm_connections] = mock_rpc + request = {} + client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_ekm_connections(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_ekm_connections_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_ekm_connections in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_ekm_connections] = mock_rpc + + request = {} + await client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_ekm_connections(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_ekm_connections_async(transport: str = 'grpc_asyncio', request_type=ekm_service.ListEkmConnectionsRequest): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ekm_service.ListEkmConnectionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEkmConnectionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_ekm_connections_async_from_dict(): + await test_list_ekm_connections_async(request_type=dict) + +def test_list_ekm_connections_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.ListEkmConnectionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + call.return_value = ekm_service.ListEkmConnectionsResponse() + client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_ekm_connections_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.ListEkmConnectionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse()) + await client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_ekm_connections_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.ListEkmConnectionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_ekm_connections( + 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_ekm_connections_flattened_error(): + client = EkmServiceClient( + credentials=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_ekm_connections( + ekm_service.ListEkmConnectionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_ekm_connections_flattened_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.ListEkmConnectionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_ekm_connections( + 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_ekm_connections_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_ekm_connections( + ekm_service.ListEkmConnectionsRequest(), + parent='parent_value', + ) + + +def test_list_ekm_connections_pager(transport_name: str = "grpc"): + client = EkmServiceClient( + 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_ekm_connections), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token='abc', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], + next_page_token='def', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ], + next_page_token='ghi', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_ekm_connections(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, ekm_service.EkmConnection) + for i in results) +def test_list_ekm_connections_pages(transport_name: str = "grpc"): + client = EkmServiceClient( + 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_ekm_connections), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token='abc', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], + next_page_token='def', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ], + next_page_token='ghi', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + pages = list(client.list_ekm_connections(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_ekm_connections_async_pager(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token='abc', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], + next_page_token='def', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ], + next_page_token='ghi', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_ekm_connections(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, ekm_service.EkmConnection) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_ekm_connections_async_pages(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token='abc', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], + next_page_token='def', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ], + next_page_token='ghi', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_ekm_connections(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + ekm_service.GetEkmConnectionRequest, + dict, +]) +def test_get_ekm_connection(request_type, transport: str = 'grpc'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + ) + response = client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ekm_service.GetEkmConnectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL + assert response.crypto_space_path == 'crypto_space_path_value' + + +def test_get_ekm_connection_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = ekm_service.GetEkmConnectionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_ekm_connection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.GetEkmConnectionRequest( + name='name_value', + ) + +def test_get_ekm_connection_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_ekm_connection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_ekm_connection] = mock_rpc + request = {} + client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_ekm_connection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_ekm_connection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_ekm_connection in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_ekm_connection] = mock_rpc + + request = {} + await client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_ekm_connection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.GetEkmConnectionRequest): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + )) + response = await client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ekm_service.GetEkmConnectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL + assert response.crypto_space_path == 'crypto_space_path_value' + + +@pytest.mark.asyncio +async def test_get_ekm_connection_async_from_dict(): + await test_get_ekm_connection_async(request_type=dict) + +def test_get_ekm_connection_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.GetEkmConnectionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + call.return_value = ekm_service.EkmConnection() + client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_ekm_connection_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.GetEkmConnectionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + await client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_ekm_connection_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_ekm_connection( + 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_ekm_connection_flattened_error(): + client = EkmServiceClient( + credentials=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_ekm_connection( + ekm_service.GetEkmConnectionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_ekm_connection_flattened_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_ekm_connection( + 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_ekm_connection_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_ekm_connection( + ekm_service.GetEkmConnectionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.CreateEkmConnectionRequest, + dict, +]) +def test_create_ekm_connection(request_type, transport: str = 'grpc'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + ) + response = client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ekm_service.CreateEkmConnectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL + assert response.crypto_space_path == 'crypto_space_path_value' + + +def test_create_ekm_connection_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = ekm_service.CreateEkmConnectionRequest( + parent='parent_value', + ekm_connection_id='ekm_connection_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_ekm_connection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.CreateEkmConnectionRequest( + parent='parent_value', + ekm_connection_id='ekm_connection_id_value', + ) + +def test_create_ekm_connection_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_ekm_connection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_ekm_connection] = mock_rpc + request = {} + client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_ekm_connection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_ekm_connection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_ekm_connection in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_ekm_connection] = mock_rpc + + request = {} + await client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_ekm_connection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.CreateEkmConnectionRequest): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + )) + response = await client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ekm_service.CreateEkmConnectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL + assert response.crypto_space_path == 'crypto_space_path_value' + + +@pytest.mark.asyncio +async def test_create_ekm_connection_async_from_dict(): + await test_create_ekm_connection_async(request_type=dict) + +def test_create_ekm_connection_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.CreateEkmConnectionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + call.return_value = ekm_service.EkmConnection() + client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_ekm_connection_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.CreateEkmConnectionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + await client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_ekm_connection_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_ekm_connection( + parent='parent_value', + ekm_connection_id='ekm_connection_id_value', + ekm_connection=ekm_service.EkmConnection(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].ekm_connection_id + mock_val = 'ekm_connection_id_value' + assert arg == mock_val + arg = args[0].ekm_connection + mock_val = ekm_service.EkmConnection(name='name_value') + assert arg == mock_val + + +def test_create_ekm_connection_flattened_error(): + client = EkmServiceClient( + credentials=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_ekm_connection( + ekm_service.CreateEkmConnectionRequest(), + parent='parent_value', + ekm_connection_id='ekm_connection_id_value', + ekm_connection=ekm_service.EkmConnection(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_ekm_connection_flattened_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_ekm_connection( + parent='parent_value', + ekm_connection_id='ekm_connection_id_value', + ekm_connection=ekm_service.EkmConnection(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].ekm_connection_id + mock_val = 'ekm_connection_id_value' + assert arg == mock_val + arg = args[0].ekm_connection + mock_val = ekm_service.EkmConnection(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_ekm_connection_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_ekm_connection( + ekm_service.CreateEkmConnectionRequest(), + parent='parent_value', + ekm_connection_id='ekm_connection_id_value', + ekm_connection=ekm_service.EkmConnection(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.UpdateEkmConnectionRequest, + dict, +]) +def test_update_ekm_connection(request_type, transport: str = 'grpc'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + ) + response = client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ekm_service.UpdateEkmConnectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL + assert response.crypto_space_path == 'crypto_space_path_value' + + +def test_update_ekm_connection_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = ekm_service.UpdateEkmConnectionRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_ekm_connection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.UpdateEkmConnectionRequest( + ) + +def test_update_ekm_connection_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_ekm_connection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_ekm_connection] = mock_rpc + request = {} + client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_ekm_connection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_ekm_connection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_ekm_connection in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_ekm_connection] = mock_rpc + + request = {} + await client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_ekm_connection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.UpdateEkmConnectionRequest): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + )) + response = await client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ekm_service.UpdateEkmConnectionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL + assert response.crypto_space_path == 'crypto_space_path_value' + + +@pytest.mark.asyncio +async def test_update_ekm_connection_async_from_dict(): + await test_update_ekm_connection_async(request_type=dict) + +def test_update_ekm_connection_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.UpdateEkmConnectionRequest() + + request.ekm_connection.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + call.return_value = ekm_service.EkmConnection() + client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'ekm_connection.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_ekm_connection_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.UpdateEkmConnectionRequest() + + request.ekm_connection.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + await client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'ekm_connection.name=name_value', + ) in kw['metadata'] + + +def test_update_ekm_connection_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_ekm_connection( + ekm_connection=ekm_service.EkmConnection(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].ekm_connection + mock_val = ekm_service.EkmConnection(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_ekm_connection_flattened_error(): + client = EkmServiceClient( + credentials=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_ekm_connection( + ekm_service.UpdateEkmConnectionRequest(), + ekm_connection=ekm_service.EkmConnection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_ekm_connection_flattened_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConnection() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_ekm_connection( + ekm_connection=ekm_service.EkmConnection(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].ekm_connection + mock_val = ekm_service.EkmConnection(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_ekm_connection_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_ekm_connection( + ekm_service.UpdateEkmConnectionRequest(), + ekm_connection=ekm_service.EkmConnection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.GetEkmConfigRequest, + dict, +]) +def test_get_ekm_config(request_type, transport: str = 'grpc'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ekm_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConfig( + name='name_value', + default_ekm_connection='default_ekm_connection_value', + ) + response = client.get_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ekm_service.GetEkmConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConfig) + assert response.name == 'name_value' + assert response.default_ekm_connection == 'default_ekm_connection_value' + + +def test_get_ekm_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = ekm_service.GetEkmConfigRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_ekm_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.GetEkmConfigRequest( + name='name_value', + ) + +def test_get_ekm_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_ekm_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_ekm_config] = mock_rpc + request = {} + client.get_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_ekm_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_ekm_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_ekm_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_ekm_config] = mock_rpc + + request = {} + await client.get_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_ekm_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_ekm_config_async(transport: str = 'grpc_asyncio', request_type=ekm_service.GetEkmConfigRequest): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig( + name='name_value', + default_ekm_connection='default_ekm_connection_value', + )) + response = await client.get_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ekm_service.GetEkmConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConfig) + assert response.name == 'name_value' + assert response.default_ekm_connection == 'default_ekm_connection_value' + + +@pytest.mark.asyncio +async def test_get_ekm_config_async_from_dict(): + await test_get_ekm_config_async(request_type=dict) + +def test_get_ekm_config_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.GetEkmConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_config), + '__call__') as call: + call.return_value = ekm_service.EkmConfig() + client.get_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_get_ekm_config_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.GetEkmConfigRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig()) + await client.get_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +def test_get_ekm_config_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_ekm_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + + +def test_get_ekm_config_flattened_error(): + client = EkmServiceClient( + credentials=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_ekm_config( + ekm_service.GetEkmConfigRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_ekm_config_flattened_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_ekm_config( + name='name_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_get_ekm_config_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_ekm_config( + ekm_service.GetEkmConfigRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.UpdateEkmConfigRequest, + dict, +]) +def test_update_ekm_config(request_type, transport: str = 'grpc'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_ekm_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConfig( + name='name_value', + default_ekm_connection='default_ekm_connection_value', + ) + response = client.update_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ekm_service.UpdateEkmConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConfig) + assert response.name == 'name_value' + assert response.default_ekm_connection == 'default_ekm_connection_value' + + +def test_update_ekm_config_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = ekm_service.UpdateEkmConfigRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_config), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_ekm_config(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.UpdateEkmConfigRequest( + ) + +def test_update_ekm_config_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_ekm_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_ekm_config] = mock_rpc + request = {} + client.update_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_ekm_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_ekm_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_ekm_config in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_ekm_config] = mock_rpc + + request = {} + await client.update_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_ekm_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_ekm_config_async(transport: str = 'grpc_asyncio', request_type=ekm_service.UpdateEkmConfigRequest): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig( + name='name_value', + default_ekm_connection='default_ekm_connection_value', + )) + response = await client.update_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ekm_service.UpdateEkmConfigRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConfig) + assert response.name == 'name_value' + assert response.default_ekm_connection == 'default_ekm_connection_value' + + +@pytest.mark.asyncio +async def test_update_ekm_config_async_from_dict(): + await test_update_ekm_config_async(request_type=dict) + +def test_update_ekm_config_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.UpdateEkmConfigRequest() + + request.ekm_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_config), + '__call__') as call: + call.return_value = ekm_service.EkmConfig() + client.update_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'ekm_config.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_ekm_config_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.UpdateEkmConfigRequest() + + request.ekm_config.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_config), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig()) + await client.update_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'ekm_config.name=name_value', + ) in kw['metadata'] + + +def test_update_ekm_config_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConfig() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_ekm_config( + ekm_config=ekm_service.EkmConfig(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].ekm_config + mock_val = ekm_service.EkmConfig(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_ekm_config_flattened_error(): + client = EkmServiceClient( + credentials=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_ekm_config( + ekm_service.UpdateEkmConfigRequest(), + ekm_config=ekm_service.EkmConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_ekm_config_flattened_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.EkmConfig() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_ekm_config( + ekm_config=ekm_service.EkmConfig(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].ekm_config + mock_val = ekm_service.EkmConfig(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_ekm_config_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_ekm_config( + ekm_service.UpdateEkmConfigRequest(), + ekm_config=ekm_service.EkmConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.VerifyConnectivityRequest, + dict, +]) +def test_verify_connectivity(request_type, transport: str = 'grpc'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.VerifyConnectivityResponse( + ) + response = client.verify_connectivity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = ekm_service.VerifyConnectivityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.VerifyConnectivityResponse) + + +def test_verify_connectivity_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = ekm_service.VerifyConnectivityRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.verify_connectivity(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == ekm_service.VerifyConnectivityRequest( + name='name_value', + ) + +def test_verify_connectivity_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.verify_connectivity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.verify_connectivity] = mock_rpc + request = {} + client.verify_connectivity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.verify_connectivity(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_verify_connectivity_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.verify_connectivity in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.verify_connectivity] = mock_rpc + + request = {} + await client.verify_connectivity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.verify_connectivity(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_verify_connectivity_async(transport: str = 'grpc_asyncio', request_type=ekm_service.VerifyConnectivityRequest): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.VerifyConnectivityResponse( + )) + response = await client.verify_connectivity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = ekm_service.VerifyConnectivityRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.VerifyConnectivityResponse) + + +@pytest.mark.asyncio +async def test_verify_connectivity_async_from_dict(): + await test_verify_connectivity_async(request_type=dict) + +def test_verify_connectivity_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.VerifyConnectivityRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), + '__call__') as call: + call.return_value = ekm_service.VerifyConnectivityResponse() + client.verify_connectivity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_verify_connectivity_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = ekm_service.VerifyConnectivityRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.VerifyConnectivityResponse()) + await client.verify_connectivity(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_verify_connectivity_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.VerifyConnectivityResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.verify_connectivity( + 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_verify_connectivity_flattened_error(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.verify_connectivity( + ekm_service.VerifyConnectivityRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_verify_connectivity_flattened_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = ekm_service.VerifyConnectivityResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.VerifyConnectivityResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.verify_connectivity( + 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_verify_connectivity_flattened_error_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.verify_connectivity( + ekm_service.VerifyConnectivityRequest(), + name='name_value', + ) + + +def test_list_ekm_connections_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_ekm_connections in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_ekm_connections] = mock_rpc + + request = {} + client.list_ekm_connections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_ekm_connections(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_ekm_connections_rest_required_fields(request_type=ekm_service.ListEkmConnectionsRequest): + transport_class = transports.EkmServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_ekm_connections._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_ekm_connections._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.ListEkmConnectionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.ListEkmConnectionsResponse.pb(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_ekm_connections(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_ekm_connections_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_ekm_connections._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_ekm_connections_rest_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.ListEkmConnectionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ekm_service.ListEkmConnectionsResponse.pb(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_ekm_connections(**mock_args) + + # Establish that the underlying call 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/*}/ekmConnections" % client.transport._host, args[1]) + + +def test_list_ekm_connections_rest_flattened_error(transport: str = 'rest'): + client = EkmServiceClient( + credentials=ga_credentials.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_ekm_connections( + ekm_service.ListEkmConnectionsRequest(), + parent='parent_value', + ) + + +def test_list_ekm_connections_rest_pager(transport: str = 'rest'): + client = EkmServiceClient( + 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 = ( + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + next_page_token='abc', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[], + next_page_token='def', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ], + next_page_token='ghi', + ), + ekm_service.ListEkmConnectionsResponse( + ekm_connections=[ + ekm_service.EkmConnection(), + ekm_service.EkmConnection(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(ekm_service.ListEkmConnectionsResponse.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_ekm_connections(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, ekm_service.EkmConnection) + for i in results) + + pages = list(client.list_ekm_connections(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_ekm_connection_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_ekm_connection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_ekm_connection] = mock_rpc + + request = {} + client.get_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_ekm_connection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_ekm_connection_rest_required_fields(request_type=ekm_service.GetEkmConnectionRequest): + transport_class = transports.EkmServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_ekm_connection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_ekm_connection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.EkmConnection.pb(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_ekm_connection(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_ekm_connection_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_ekm_connection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_ekm_connection_rest_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ekm_service.EkmConnection.pb(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_ekm_connection(**mock_args) + + # Establish that the underlying call 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/*/ekmConnections/*}" % client.transport._host, args[1]) + + +def test_get_ekm_connection_rest_flattened_error(transport: str = 'rest'): + client = EkmServiceClient( + credentials=ga_credentials.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_ekm_connection( + ekm_service.GetEkmConnectionRequest(), + name='name_value', + ) + + +def test_create_ekm_connection_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_ekm_connection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_ekm_connection] = mock_rpc + + request = {} + client.create_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_ekm_connection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_ekm_connection_rest_required_fields(request_type=ekm_service.CreateEkmConnectionRequest): + transport_class = transports.EkmServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["ekm_connection_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "ekmConnectionId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_ekm_connection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "ekmConnectionId" in jsonified_request + assert jsonified_request["ekmConnectionId"] == request_init["ekm_connection_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["ekmConnectionId"] = 'ekm_connection_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_ekm_connection._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("ekm_connection_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "ekmConnectionId" in jsonified_request + assert jsonified_request["ekmConnectionId"] == 'ekm_connection_id_value' + + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.EkmConnection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_ekm_connection(request) + + expected_params = [ + ( + "ekmConnectionId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_ekm_connection_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_ekm_connection._get_unset_required_fields({}) + assert set(unset_fields) == (set(("ekmConnectionId", )) & set(("parent", "ekmConnectionId", "ekmConnection", ))) + + +def test_create_ekm_connection_rest_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection() + + # 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', + ekm_connection_id='ekm_connection_id_value', + ekm_connection=ekm_service.EkmConnection(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ekm_service.EkmConnection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_ekm_connection(**mock_args) + + # Establish that the underlying call 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/*}/ekmConnections" % client.transport._host, args[1]) + + +def test_create_ekm_connection_rest_flattened_error(transport: str = 'rest'): + client = EkmServiceClient( + credentials=ga_credentials.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_ekm_connection( + ekm_service.CreateEkmConnectionRequest(), + parent='parent_value', + ekm_connection_id='ekm_connection_id_value', + ekm_connection=ekm_service.EkmConnection(name='name_value'), + ) + + +def test_update_ekm_connection_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_ekm_connection in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_ekm_connection] = mock_rpc + + request = {} + client.update_ekm_connection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_ekm_connection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_ekm_connection_rest_required_fields(request_type=ekm_service.UpdateEkmConnectionRequest): + transport_class = transports.EkmServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_ekm_connection._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_ekm_connection._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 = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection() + # 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 + + # Convert return value to protobuf type + return_value = ekm_service.EkmConnection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_ekm_connection(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_ekm_connection_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_ekm_connection._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("ekmConnection", "updateMask", ))) + + +def test_update_ekm_connection_rest_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection() + + # get arguments that satisfy an http rule for this method + sample_request = {'ekm_connection': {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'}} + + # get truthy value for each flattened field + mock_args = dict( + ekm_connection=ekm_service.EkmConnection(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 + # Convert return value to protobuf type + return_value = ekm_service.EkmConnection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_ekm_connection(**mock_args) + + # Establish that the underlying call 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/{ekm_connection.name=projects/*/locations/*/ekmConnections/*}" % client.transport._host, args[1]) + + +def test_update_ekm_connection_rest_flattened_error(transport: str = 'rest'): + client = EkmServiceClient( + credentials=ga_credentials.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_ekm_connection( + ekm_service.UpdateEkmConnectionRequest(), + ekm_connection=ekm_service.EkmConnection(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_get_ekm_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_ekm_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_ekm_config] = mock_rpc + + request = {} + client.get_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_ekm_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_ekm_config_rest_required_fields(request_type=ekm_service.GetEkmConfigRequest): + transport_class = transports.EkmServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_ekm_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_ekm_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConfig() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.EkmConfig.pb(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_ekm_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_ekm_config_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_ekm_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_ekm_config_rest_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/ekmConfig'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ekm_service.EkmConfig.pb(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_ekm_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{name=projects/*/locations/*/ekmConfig}" % client.transport._host, args[1]) + + +def test_get_ekm_config_rest_flattened_error(transport: str = 'rest'): + client = EkmServiceClient( + credentials=ga_credentials.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_ekm_config( + ekm_service.GetEkmConfigRequest(), + name='name_value', + ) + + +def test_update_ekm_config_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_ekm_config in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_ekm_config] = mock_rpc + + request = {} + client.update_ekm_config(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_ekm_config(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_ekm_config_rest_required_fields(request_type=ekm_service.UpdateEkmConfigRequest): + transport_class = transports.EkmServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_ekm_config._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_ekm_config._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 = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConfig() + # 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 + + # Convert return value to protobuf type + return_value = ekm_service.EkmConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_ekm_config(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_ekm_config_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_ekm_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("ekmConfig", "updateMask", ))) + + +def test_update_ekm_config_rest_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {'ekm_config': {'name': 'projects/sample1/locations/sample2/ekmConfig'}} + + # get truthy value for each flattened field + mock_args = dict( + ekm_config=ekm_service.EkmConfig(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 + # Convert return value to protobuf type + return_value = ekm_service.EkmConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_ekm_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{ekm_config.name=projects/*/locations/*/ekmConfig}" % client.transport._host, args[1]) + + +def test_update_ekm_config_rest_flattened_error(transport: str = 'rest'): + client = EkmServiceClient( + credentials=ga_credentials.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_ekm_config( + ekm_service.UpdateEkmConfigRequest(), + ekm_config=ekm_service.EkmConfig(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_verify_connectivity_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.verify_connectivity in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.verify_connectivity] = mock_rpc + + request = {} + client.verify_connectivity(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.verify_connectivity(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_verify_connectivity_rest_required_fields(request_type=ekm_service.VerifyConnectivityRequest): + transport_class = transports.EkmServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).verify_connectivity._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).verify_connectivity._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ekm_service.VerifyConnectivityResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.VerifyConnectivityResponse.pb(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.verify_connectivity(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_verify_connectivity_rest_unset_required_fields(): + transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.verify_connectivity._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_verify_connectivity_rest_flattened(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.VerifyConnectivityResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ekm_service.VerifyConnectivityResponse.pb(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.verify_connectivity(**mock_args) + + # Establish that the underlying call 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/*/ekmConnections/*}:verifyConnectivity" % client.transport._host, args[1]) + + +def test_verify_connectivity_rest_flattened_error(transport: str = 'rest'): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.verify_connectivity( + ekm_service.VerifyConnectivityRequest(), + name='name_value', + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = EkmServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = EkmServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.EkmServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.EkmServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.EkmServiceGrpcTransport, + transports.EkmServiceGrpcAsyncIOTransport, + transports.EkmServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = EkmServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_ekm_connections_empty_call_grpc(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + call.return_value = ekm_service.ListEkmConnectionsResponse() + client.list_ekm_connections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.ListEkmConnectionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_ekm_connection_empty_call_grpc(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + call.return_value = ekm_service.EkmConnection() + client.get_ekm_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.GetEkmConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_ekm_connection_empty_call_grpc(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + call.return_value = ekm_service.EkmConnection() + client.create_ekm_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.CreateEkmConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_ekm_connection_empty_call_grpc(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + call.return_value = ekm_service.EkmConnection() + client.update_ekm_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.UpdateEkmConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_ekm_config_empty_call_grpc(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_config), + '__call__') as call: + call.return_value = ekm_service.EkmConfig() + client.get_ekm_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.GetEkmConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_ekm_config_empty_call_grpc(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_config), + '__call__') as call: + call.return_value = ekm_service.EkmConfig() + client.update_ekm_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.UpdateEkmConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_verify_connectivity_empty_call_grpc(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), + '__call__') as call: + call.return_value = ekm_service.VerifyConnectivityResponse() + client.verify_connectivity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.VerifyConnectivityRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = EkmServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_ekm_connections_empty_call_grpc_asyncio(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_ekm_connections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.ListEkmConnectionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_ekm_connection_empty_call_grpc_asyncio(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + )) + await client.get_ekm_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.GetEkmConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_ekm_connection_empty_call_grpc_asyncio(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + )) + await client.create_ekm_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.CreateEkmConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_ekm_connection_empty_call_grpc_asyncio(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + )) + await client.update_ekm_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.UpdateEkmConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_ekm_config_empty_call_grpc_asyncio(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig( + name='name_value', + default_ekm_connection='default_ekm_connection_value', + )) + await client.get_ekm_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.GetEkmConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_ekm_config_empty_call_grpc_asyncio(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_config), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig( + name='name_value', + default_ekm_connection='default_ekm_connection_value', + )) + await client.update_ekm_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.UpdateEkmConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_verify_connectivity_empty_call_grpc_asyncio(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.VerifyConnectivityResponse( + )) + await client.verify_connectivity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.VerifyConnectivityRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = EkmServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_ekm_connections_rest_bad_request(request_type=ekm_service.ListEkmConnectionsRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_ekm_connections(request) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.ListEkmConnectionsRequest, + dict, +]) +def test_list_ekm_connections_rest_call_success(request_type): + client = EkmServiceClient( + 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 = ekm_service.ListEkmConnectionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.ListEkmConnectionsResponse.pb(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_ekm_connections(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEkmConnectionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_ekm_connections_rest_interceptors(null_interceptor): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), + ) + client = EkmServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "post_list_ekm_connections") as post, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "pre_list_ekm_connections") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.ListEkmConnectionsRequest.pb(ekm_service.ListEkmConnectionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = ekm_service.ListEkmConnectionsResponse.to_json(ekm_service.ListEkmConnectionsResponse()) + req.return_value.content = return_value + + request = ekm_service.ListEkmConnectionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.ListEkmConnectionsResponse() + + client.list_ekm_connections(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_ekm_connection_rest_bad_request(request_type=ekm_service.GetEkmConnectionRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_ekm_connection(request) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.GetEkmConnectionRequest, + dict, +]) +def test_get_ekm_connection_rest_call_success(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.EkmConnection.pb(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_ekm_connection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL + assert response.crypto_space_path == 'crypto_space_path_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_ekm_connection_rest_interceptors(null_interceptor): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), + ) + client = EkmServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "post_get_ekm_connection") as post, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "pre_get_ekm_connection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.GetEkmConnectionRequest.pb(ekm_service.GetEkmConnectionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = ekm_service.EkmConnection.to_json(ekm_service.EkmConnection()) + req.return_value.content = return_value + + request = ekm_service.GetEkmConnectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.EkmConnection() + + client.get_ekm_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_ekm_connection_rest_bad_request(request_type=ekm_service.CreateEkmConnectionRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_ekm_connection(request) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.CreateEkmConnectionRequest, + dict, +]) +def test_create_ekm_connection_rest_call_success(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["ekm_connection"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'service_resolvers': [{'service_directory_service': 'service_directory_service_value', 'endpoint_filter': 'endpoint_filter_value', 'hostname': 'hostname_value', 'server_certificates': [{'raw_der': b'raw_der_blob', 'parsed': True, 'issuer': 'issuer_value', 'subject': 'subject_value', 'subject_alternative_dns_names': ['subject_alternative_dns_names_value1', 'subject_alternative_dns_names_value2'], 'not_before_time': {}, 'not_after_time': {}, 'serial_number': 'serial_number_value', 'sha256_fingerprint': 'sha256_fingerprint_value'}]}], 'etag': 'etag_value', 'key_management_mode': 1, 'crypto_space_path': 'crypto_space_path_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ekm_service.CreateEkmConnectionRequest.meta.fields["ekm_connection"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["ekm_connection"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["ekm_connection"][field])): + del request_init["ekm_connection"][field][i][subfield] + else: + del request_init["ekm_connection"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.EkmConnection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_ekm_connection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL + assert response.crypto_space_path == 'crypto_space_path_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_ekm_connection_rest_interceptors(null_interceptor): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), + ) + client = EkmServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "post_create_ekm_connection") as post, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "pre_create_ekm_connection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.CreateEkmConnectionRequest.pb(ekm_service.CreateEkmConnectionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = ekm_service.EkmConnection.to_json(ekm_service.EkmConnection()) + req.return_value.content = return_value + + request = ekm_service.CreateEkmConnectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.EkmConnection() + + client.create_ekm_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_ekm_connection_rest_bad_request(request_type=ekm_service.UpdateEkmConnectionRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'ekm_connection': {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_ekm_connection(request) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.UpdateEkmConnectionRequest, + dict, +]) +def test_update_ekm_connection_rest_call_success(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'ekm_connection': {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'}} + request_init["ekm_connection"] = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'service_resolvers': [{'service_directory_service': 'service_directory_service_value', 'endpoint_filter': 'endpoint_filter_value', 'hostname': 'hostname_value', 'server_certificates': [{'raw_der': b'raw_der_blob', 'parsed': True, 'issuer': 'issuer_value', 'subject': 'subject_value', 'subject_alternative_dns_names': ['subject_alternative_dns_names_value1', 'subject_alternative_dns_names_value2'], 'not_before_time': {}, 'not_after_time': {}, 'serial_number': 'serial_number_value', 'sha256_fingerprint': 'sha256_fingerprint_value'}]}], 'etag': 'etag_value', 'key_management_mode': 1, 'crypto_space_path': 'crypto_space_path_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ekm_service.UpdateEkmConnectionRequest.meta.fields["ekm_connection"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["ekm_connection"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["ekm_connection"][field])): + del request_init["ekm_connection"][field][i][subfield] + else: + del request_init["ekm_connection"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConnection( + name='name_value', + etag='etag_value', + key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, + crypto_space_path='crypto_space_path_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.EkmConnection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_ekm_connection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConnection) + assert response.name == 'name_value' + assert response.etag == 'etag_value' + assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL + assert response.crypto_space_path == 'crypto_space_path_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_ekm_connection_rest_interceptors(null_interceptor): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), + ) + client = EkmServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "post_update_ekm_connection") as post, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "pre_update_ekm_connection") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.UpdateEkmConnectionRequest.pb(ekm_service.UpdateEkmConnectionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = ekm_service.EkmConnection.to_json(ekm_service.EkmConnection()) + req.return_value.content = return_value + + request = ekm_service.UpdateEkmConnectionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.EkmConnection() + + client.update_ekm_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_ekm_config_rest_bad_request(request_type=ekm_service.GetEkmConfigRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/ekmConfig'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_ekm_config(request) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.GetEkmConfigRequest, + dict, +]) +def test_get_ekm_config_rest_call_success(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/ekmConfig'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConfig( + name='name_value', + default_ekm_connection='default_ekm_connection_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.EkmConfig.pb(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_ekm_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConfig) + assert response.name == 'name_value' + assert response.default_ekm_connection == 'default_ekm_connection_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_ekm_config_rest_interceptors(null_interceptor): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), + ) + client = EkmServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "post_get_ekm_config") as post, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "pre_get_ekm_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.GetEkmConfigRequest.pb(ekm_service.GetEkmConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = ekm_service.EkmConfig.to_json(ekm_service.EkmConfig()) + req.return_value.content = return_value + + request = ekm_service.GetEkmConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.EkmConfig() + + client.get_ekm_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_ekm_config_rest_bad_request(request_type=ekm_service.UpdateEkmConfigRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'ekm_config': {'name': 'projects/sample1/locations/sample2/ekmConfig'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_ekm_config(request) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.UpdateEkmConfigRequest, + dict, +]) +def test_update_ekm_config_rest_call_success(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'ekm_config': {'name': 'projects/sample1/locations/sample2/ekmConfig'}} + request_init["ekm_config"] = {'name': 'projects/sample1/locations/sample2/ekmConfig', 'default_ekm_connection': 'default_ekm_connection_value'} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = ekm_service.UpdateEkmConfigRequest.meta.fields["ekm_config"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["ekm_config"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["ekm_config"][field])): + del request_init["ekm_config"][field][i][subfield] + else: + del request_init["ekm_config"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.EkmConfig( + name='name_value', + default_ekm_connection='default_ekm_connection_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.EkmConfig.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_ekm_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.EkmConfig) + assert response.name == 'name_value' + assert response.default_ekm_connection == 'default_ekm_connection_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_ekm_config_rest_interceptors(null_interceptor): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), + ) + client = EkmServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "post_update_ekm_config") as post, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "pre_update_ekm_config") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.UpdateEkmConfigRequest.pb(ekm_service.UpdateEkmConfigRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = ekm_service.EkmConfig.to_json(ekm_service.EkmConfig()) + req.return_value.content = return_value + + request = ekm_service.UpdateEkmConfigRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.EkmConfig() + + client.update_ekm_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_verify_connectivity_rest_bad_request(request_type=ekm_service.VerifyConnectivityRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.verify_connectivity(request) + + +@pytest.mark.parametrize("request_type", [ + ekm_service.VerifyConnectivityRequest, + dict, +]) +def test_verify_connectivity_rest_call_success(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = ekm_service.VerifyConnectivityResponse( + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = ekm_service.VerifyConnectivityResponse.pb(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.verify_connectivity(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, ekm_service.VerifyConnectivityResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_verify_connectivity_rest_interceptors(null_interceptor): + transport = transports.EkmServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), + ) + client = EkmServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "post_verify_connectivity") as post, \ + mock.patch.object(transports.EkmServiceRestInterceptor, "pre_verify_connectivity") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = ekm_service.VerifyConnectivityRequest.pb(ekm_service.VerifyConnectivityRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = ekm_service.VerifyConnectivityResponse.to_json(ekm_service.VerifyConnectivityResponse()) + req.return_value.content = return_value + + request = ekm_service.VerifyConnectivityRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ekm_service.VerifyConnectivityResponse() + + client.verify_connectivity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_initialize_client_w_rest(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_ekm_connections_empty_call_rest(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_ekm_connections), + '__call__') as call: + client.list_ekm_connections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.ListEkmConnectionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_ekm_connection_empty_call_rest(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_connection), + '__call__') as call: + client.get_ekm_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.GetEkmConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_ekm_connection_empty_call_rest(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_ekm_connection), + '__call__') as call: + client.create_ekm_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.CreateEkmConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_ekm_connection_empty_call_rest(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_connection), + '__call__') as call: + client.update_ekm_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.UpdateEkmConnectionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_ekm_config_empty_call_rest(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_ekm_config), + '__call__') as call: + client.get_ekm_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.GetEkmConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_ekm_config_empty_call_rest(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_ekm_config), + '__call__') as call: + client.update_ekm_config(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.UpdateEkmConfigRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_verify_connectivity_empty_call_rest(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.verify_connectivity), + '__call__') as call: + client.verify_connectivity(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ekm_service.VerifyConnectivityRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.EkmServiceGrpcTransport, + ) + +def test_ekm_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.EkmServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_ekm_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.EkmServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_ekm_connections', + 'get_ekm_connection', + 'create_ekm_connection', + 'update_ekm_connection', + 'get_ekm_config', + 'update_ekm_config', + 'verify_connectivity', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + ) + 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_ekm_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EkmServiceTransport( + 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', + 'https://www.googleapis.com/auth/cloudkms', +), + quota_project_id="octopus", + ) + + +def test_ekm_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.EkmServiceTransport() + adc.assert_called_once() + + +def test_ekm_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + EkmServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EkmServiceGrpcTransport, + transports.EkmServiceGrpcAsyncIOTransport, + ], +) +def test_ekm_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloudkms',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.EkmServiceGrpcTransport, + transports.EkmServiceGrpcAsyncIOTransport, + transports.EkmServiceRestTransport, + ], +) +def test_ekm_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.EkmServiceGrpcTransport, grpc_helpers), + (transports.EkmServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_ekm_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + scopes=["1", "2"], + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) +def test_ekm_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_ekm_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.EkmServiceRestTransport ( + 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_ekm_service_host_no_port(transport_name): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudkms.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_ekm_service_host_with_port(transport_name): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudkms.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudkms.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_ekm_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = EkmServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = EkmServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_ekm_connections._session + session2 = client2.transport.list_ekm_connections._session + assert session1 != session2 + session1 = client1.transport.get_ekm_connection._session + session2 = client2.transport.get_ekm_connection._session + assert session1 != session2 + session1 = client1.transport.create_ekm_connection._session + session2 = client2.transport.create_ekm_connection._session + assert session1 != session2 + session1 = client1.transport.update_ekm_connection._session + session2 = client2.transport.update_ekm_connection._session + assert session1 != session2 + session1 = client1.transport.get_ekm_config._session + session2 = client2.transport.get_ekm_config._session + assert session1 != session2 + session1 = client1.transport.update_ekm_config._session + session2 = client2.transport.update_ekm_config._session + assert session1 != session2 + session1 = client1.transport.verify_connectivity._session + session2 = client2.transport.verify_connectivity._session + assert session1 != session2 +def test_ekm_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EkmServiceGrpcTransport( + 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_ekm_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.EkmServiceGrpcAsyncIOTransport( + 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.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) +def test_ekm_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) +def test_ekm_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_ekm_config_path(): + project = "squid" + location = "clam" + expected = "projects/{project}/locations/{location}/ekmConfig".format(project=project, location=location, ) + actual = EkmServiceClient.ekm_config_path(project, location) + assert expected == actual + + +def test_parse_ekm_config_path(): + expected = { + "project": "whelk", + "location": "octopus", + } + path = EkmServiceClient.ekm_config_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_ekm_config_path(path) + assert expected == actual + +def test_ekm_connection_path(): + project = "oyster" + location = "nudibranch" + ekm_connection = "cuttlefish" + expected = "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format(project=project, location=location, ekm_connection=ekm_connection, ) + actual = EkmServiceClient.ekm_connection_path(project, location, ekm_connection) + assert expected == actual + + +def test_parse_ekm_connection_path(): + expected = { + "project": "mussel", + "location": "winkle", + "ekm_connection": "nautilus", + } + path = EkmServiceClient.ekm_connection_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_ekm_connection_path(path) + assert expected == actual + +def test_service_path(): + project = "scallop" + location = "abalone" + namespace = "squid" + service = "clam" + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) + actual = EkmServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "whelk", + "location": "octopus", + "namespace": "oyster", + "service": "nudibranch", + } + path = EkmServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_service_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = EkmServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = EkmServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = EkmServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = EkmServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = EkmServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = EkmServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = EkmServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = EkmServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.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 = EkmServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = EkmServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = EkmServiceClient.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.EkmServiceTransport, '_prep_wrapped_messages') as prep: + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.EkmServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = EkmServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_get_operation(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = EkmServiceClient( + 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 = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = EkmServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = EkmServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = EkmServiceClient( + 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", [ + (EkmServiceClient, transports.EkmServiceGrpcTransport), + (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_key_management_service.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_key_management_service.py new file mode 100644 index 000000000000..6ee519ae5ede --- /dev/null +++ b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -0,0 +1,22906 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +import grpc +from grpc.experimental import aio +from collections.abc import Iterable, AsyncIterable +from google.protobuf import json_format +import json +import math +import pytest +from google.api_core import api_core_version +from proto.marshal.rules.dates import DurationRule, TimestampRule +from proto.marshal.rules import wrappers +from requests import Response +from requests import Request, PreparedRequest +from requests.sessions import Session +from google.protobuf import json_format + +try: + from google.auth.aio import credentials as ga_credentials_async + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.api_core import path_template +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.kms_v1.services.key_management_service import KeyManagementServiceAsyncClient +from google.cloud.kms_v1.services.key_management_service import KeyManagementServiceClient +from google.cloud.kms_v1.services.key_management_service import pagers +from google.cloud.kms_v1.services.key_management_service import transports +from google.cloud.kms_v1.types import resources +from google.cloud.kms_v1.types import service +from google.cloud.location import locations_pb2 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.protobuf import wrappers_pb2 # type: ignore +import google.auth + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert KeyManagementServiceClient._get_default_mtls_endpoint(None) is None + assert KeyManagementServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert KeyManagementServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + assert KeyManagementServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint + assert KeyManagementServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint + assert KeyManagementServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + +def test__read_environment_variables(): + assert KeyManagementServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert KeyManagementServiceClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert KeyManagementServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + KeyManagementServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert KeyManagementServiceClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert KeyManagementServiceClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert KeyManagementServiceClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + KeyManagementServiceClient._read_environment_variables() + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert KeyManagementServiceClient._read_environment_variables() == (False, "auto", "foo.com") + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert KeyManagementServiceClient._get_client_cert_source(None, False) is None + assert KeyManagementServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert KeyManagementServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source + + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): + assert KeyManagementServiceClient._get_client_cert_source(None, True) is mock_default_cert_source + assert KeyManagementServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source + +@mock.patch.object(KeyManagementServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceClient)) +@mock.patch.object(KeyManagementServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceAsyncClient)) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = KeyManagementServiceClient._DEFAULT_UNIVERSE + default_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + assert KeyManagementServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override + assert KeyManagementServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT + assert KeyManagementServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint + assert KeyManagementServiceClient._get_api_endpoint(None, None, default_universe, "always") == KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT + assert KeyManagementServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT + assert KeyManagementServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint + assert KeyManagementServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint + + with pytest.raises(MutualTLSChannelError) as excinfo: + KeyManagementServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") + assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert KeyManagementServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain + assert KeyManagementServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env + assert KeyManagementServiceClient._get_universe_domain(None, None) == KeyManagementServiceClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + KeyManagementServiceClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize("client_class,transport_name", [ + (KeyManagementServiceClient, "grpc"), + (KeyManagementServiceAsyncClient, "grpc_asyncio"), + (KeyManagementServiceClient, "rest"), +]) +def test_key_management_service_client_from_service_account_info(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudkms.googleapis.com' + ) + + +@pytest.mark.parametrize("transport_class,transport_name", [ + (transports.KeyManagementServiceGrpcTransport, "grpc"), + (transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.KeyManagementServiceRestTransport, "rest"), +]) +def test_key_management_service_client_service_account_always_use_jwt(transport_class, transport_name): + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize("client_class,transport_name", [ + (KeyManagementServiceClient, "grpc"), + (KeyManagementServiceAsyncClient, "grpc_asyncio"), + (KeyManagementServiceClient, "rest"), +]) +def test_key_management_service_client_from_service_account_file(client_class, transport_name): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else + 'https://cloudkms.googleapis.com' + ) + + +def test_key_management_service_client_get_transport_class(): + transport = KeyManagementServiceClient.get_transport_class() + available_transports = [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceRestTransport, + ] + assert transport in available_transports + + transport = KeyManagementServiceClient.get_transport_class("grpc") + assert transport == transports.KeyManagementServiceGrpcTransport + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc"), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (KeyManagementServiceClient, transports.KeyManagementServiceRestTransport, "rest"), +]) +@mock.patch.object(KeyManagementServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceClient)) +@mock.patch.object(KeyManagementServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceAsyncClient)) +def test_key_management_service_client_client_options(client_class, transport_class, transport_name): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(KeyManagementServiceClient, '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(KeyManagementServiceClient, 'get_transport_class') as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions(api_audience="https://language.googleapis.com") + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com" + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", "true"), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", "false"), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), + (KeyManagementServiceClient, transports.KeyManagementServiceRestTransport, "rest", "true"), + (KeyManagementServiceClient, transports.KeyManagementServiceRestTransport, "rest", "false"), +]) +@mock.patch.object(KeyManagementServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceClient)) +@mock.patch.object(KeyManagementServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceAsyncClient)) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_key_management_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): + with mock.patch.object(transport_class, '__init__') as patched: + with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ + KeyManagementServiceClient, KeyManagementServiceAsyncClient +]) +@mock.patch.object(KeyManagementServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KeyManagementServiceClient)) +@mock.patch.object(KeyManagementServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KeyManagementServiceAsyncClient)) +def test_key_management_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): + with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + +@pytest.mark.parametrize("client_class", [ + KeyManagementServiceClient, KeyManagementServiceAsyncClient +]) +@mock.patch.object(KeyManagementServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceClient)) +@mock.patch.object(KeyManagementServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceAsyncClient)) +def test_key_management_service_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = KeyManagementServiceClient._DEFAULT_UNIVERSE + default_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) + mock_universe = "bar.com" + mock_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): + options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + else: + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) + assert client.universe_domain == (mock_universe if universe_exists else default_universe) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize("client_class,transport_class,transport_name", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc"), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (KeyManagementServiceClient, transports.KeyManagementServiceRestTransport, "rest"), +]) +def test_key_management_service_client_client_options_scopes(client_class, transport_class, transport_name): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", grpc_helpers), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), + (KeyManagementServiceClient, transports.KeyManagementServiceRestTransport, "rest", None), +]) +def test_key_management_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + +def test_key_management_service_client_client_options_from_dict(): + with mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceGrpcTransport.__init__') as grpc_transport: + grpc_transport.return_value = None + client = KeyManagementServiceClient( + 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", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", grpc_helpers), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), +]) +def test_key_management_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): + # Check the case credentials file is provided. + options = client_options.ClientOptions( + credentials_file="credentials.json" + ) + + with mock.patch.object(transport_class, '__init__') as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + scopes=None, + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [ + service.ListKeyRingsRequest, + dict, +]) +def test_list_key_rings(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_rings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListKeyRingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_key_rings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListKeyRingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyRingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_key_rings_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListKeyRingsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_key_rings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListKeyRingsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_key_rings_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_key_rings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_key_rings] = mock_rpc + request = {} + client.list_key_rings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_key_rings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_key_rings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_key_rings in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_key_rings] = mock_rpc + + request = {} + await client.list_key_rings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_key_rings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_key_rings_async(transport: str = 'grpc_asyncio', request_type=service.ListKeyRingsRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_key_rings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListKeyRingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyRingsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_key_rings_async_from_dict(): + await test_list_key_rings_async(request_type=dict) + +def test_list_key_rings_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListKeyRingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + call.return_value = service.ListKeyRingsResponse() + client.list_key_rings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_key_rings_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListKeyRingsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse()) + await client.list_key_rings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_key_rings_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListKeyRingsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_key_rings( + 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_key_rings_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_key_rings( + service.ListKeyRingsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_key_rings_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListKeyRingsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_key_rings( + 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_key_rings_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_key_rings( + service.ListKeyRingsRequest(), + parent='parent_value', + ) + + +def test_list_key_rings_pager(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_key_rings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + resources.KeyRing(), + ], + next_page_token='abc', + ), + service.ListKeyRingsResponse( + key_rings=[], + next_page_token='def', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + ], + next_page_token='ghi', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_key_rings(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.KeyRing) + for i in results) +def test_list_key_rings_pages(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_key_rings), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + resources.KeyRing(), + ], + next_page_token='abc', + ), + service.ListKeyRingsResponse( + key_rings=[], + next_page_token='def', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + ], + next_page_token='ghi', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + ], + ), + RuntimeError, + ) + pages = list(client.list_key_rings(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_key_rings_async_pager(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + resources.KeyRing(), + ], + next_page_token='abc', + ), + service.ListKeyRingsResponse( + key_rings=[], + next_page_token='def', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + ], + next_page_token='ghi', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_key_rings(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, resources.KeyRing) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_key_rings_async_pages(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + resources.KeyRing(), + ], + next_page_token='abc', + ), + service.ListKeyRingsResponse( + key_rings=[], + next_page_token='def', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + ], + next_page_token='ghi', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_key_rings(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.ListCryptoKeysRequest, + dict, +]) +def test_list_crypto_keys(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crypto_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeysResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_crypto_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListCryptoKeysRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeysPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_crypto_keys_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListCryptoKeysRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_crypto_keys(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListCryptoKeysRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_crypto_keys_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_crypto_keys in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_crypto_keys] = mock_rpc + request = {} + client.list_crypto_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_crypto_keys(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_crypto_keys_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_crypto_keys in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_crypto_keys] = mock_rpc + + request = {} + await client.list_crypto_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_crypto_keys(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_crypto_keys_async(transport: str = 'grpc_asyncio', request_type=service.ListCryptoKeysRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_crypto_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListCryptoKeysRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeysAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_crypto_keys_async_from_dict(): + await test_list_crypto_keys_async(request_type=dict) + +def test_list_crypto_keys_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListCryptoKeysRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + call.return_value = service.ListCryptoKeysResponse() + client.list_crypto_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_list_crypto_keys_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListCryptoKeysRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse()) + await client.list_crypto_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +def test_list_crypto_keys_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeysResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_crypto_keys( + 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_crypto_keys_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_crypto_keys( + service.ListCryptoKeysRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_crypto_keys_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeysResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_crypto_keys( + 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_crypto_keys_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_crypto_keys( + service.ListCryptoKeysRequest(), + parent='parent_value', + ) + + +def test_list_crypto_keys_pager(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_crypto_keys), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + resources.CryptoKey(), + ], + next_page_token='abc', + ), + service.ListCryptoKeysResponse( + crypto_keys=[], + next_page_token='def', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_crypto_keys(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CryptoKey) + for i in results) +def test_list_crypto_keys_pages(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_crypto_keys), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + resources.CryptoKey(), + ], + next_page_token='abc', + ), + service.ListCryptoKeysResponse( + crypto_keys=[], + next_page_token='def', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + ], + ), + RuntimeError, + ) + pages = list(client.list_crypto_keys(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_crypto_keys_async_pager(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + resources.CryptoKey(), + ], + next_page_token='abc', + ), + service.ListCryptoKeysResponse( + crypto_keys=[], + next_page_token='def', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_crypto_keys(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, resources.CryptoKey) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_crypto_keys_async_pages(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + resources.CryptoKey(), + ], + next_page_token='abc', + ), + service.ListCryptoKeysResponse( + crypto_keys=[], + next_page_token='def', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_crypto_keys(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.ListCryptoKeyVersionsRequest, + dict, +]) +def test_list_crypto_key_versions(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crypto_key_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeyVersionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_crypto_key_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListCryptoKeyVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeyVersionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_crypto_key_versions_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListCryptoKeyVersionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_crypto_key_versions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListCryptoKeyVersionsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_crypto_key_versions_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_crypto_key_versions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_crypto_key_versions] = mock_rpc + request = {} + client.list_crypto_key_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_crypto_key_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_crypto_key_versions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_crypto_key_versions in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_crypto_key_versions] = mock_rpc + + request = {} + await client.list_crypto_key_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_crypto_key_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_crypto_key_versions_async(transport: str = 'grpc_asyncio', request_type=service.ListCryptoKeyVersionsRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_crypto_key_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListCryptoKeyVersionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeyVersionsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_crypto_key_versions_async_from_dict(): + await test_list_crypto_key_versions_async(request_type=dict) + +def test_list_crypto_key_versions_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListCryptoKeyVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + call.return_value = service.ListCryptoKeyVersionsResponse() + client.list_crypto_key_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_crypto_key_versions_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListCryptoKeyVersionsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse()) + await client.list_crypto_key_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_crypto_key_versions_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeyVersionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_crypto_key_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_crypto_key_versions_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_crypto_key_versions( + service.ListCryptoKeyVersionsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_crypto_key_versions_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListCryptoKeyVersionsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_crypto_key_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_crypto_key_versions_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_crypto_key_versions( + service.ListCryptoKeyVersionsRequest(), + parent='parent_value', + ) + + +def test_list_crypto_key_versions_pager(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_crypto_key_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + next_page_token='abc', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[], + next_page_token='def', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_crypto_key_versions(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CryptoKeyVersion) + for i in results) +def test_list_crypto_key_versions_pages(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_crypto_key_versions), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + next_page_token='abc', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[], + next_page_token='def', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + ), + RuntimeError, + ) + pages = list(client.list_crypto_key_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_crypto_key_versions_async_pager(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + next_page_token='abc', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[], + next_page_token='def', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_crypto_key_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, resources.CryptoKeyVersion) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_crypto_key_versions_async_pages(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + next_page_token='abc', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[], + next_page_token='def', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_crypto_key_versions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.ListImportJobsRequest, + dict, +]) +def test_list_import_jobs(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_import_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListImportJobsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + response = client.list_import_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListImportJobsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImportJobsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +def test_list_import_jobs_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListImportJobsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.list_import_jobs(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListImportJobsRequest( + parent='parent_value', + page_token='page_token_value', + filter='filter_value', + order_by='order_by_value', + ) + +def test_list_import_jobs_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_import_jobs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_import_jobs] = mock_rpc + request = {} + client.list_import_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_import_jobs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_import_jobs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.list_import_jobs in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.list_import_jobs] = mock_rpc + + request = {} + await client.list_import_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_import_jobs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_list_import_jobs_async(transport: str = 'grpc_asyncio', request_type=service.ListImportJobsRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + response = await client.list_import_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListImportJobsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImportJobsAsyncPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.asyncio +async def test_list_import_jobs_async_from_dict(): + await test_list_import_jobs_async(request_type=dict) + +def test_list_import_jobs_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListImportJobsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + call.return_value = service.ListImportJobsResponse() + client.list_import_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_import_jobs_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListImportJobsRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse()) + await client.list_import_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_import_jobs_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListImportJobsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_import_jobs( + 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_import_jobs_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_import_jobs( + service.ListImportJobsRequest(), + parent='parent_value', + ) + +@pytest.mark.asyncio +async def test_list_import_jobs_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListImportJobsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_import_jobs( + 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_import_jobs_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_import_jobs( + service.ListImportJobsRequest(), + parent='parent_value', + ) + + +def test_list_import_jobs_pager(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_import_jobs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + resources.ImportJob(), + ], + next_page_token='abc', + ), + service.ListImportJobsResponse( + import_jobs=[], + next_page_token='def', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + ], + next_page_token='ghi', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata(( + ('parent', ''), + )), + ) + pager = client.list_import_jobs(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ImportJob) + for i in results) +def test_list_import_jobs_pages(transport_name: str = "grpc"): + client = KeyManagementServiceClient( + 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_import_jobs), + '__call__') as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + resources.ImportJob(), + ], + next_page_token='abc', + ), + service.ListImportJobsResponse( + import_jobs=[], + next_page_token='def', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + ], + next_page_token='ghi', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + ], + ), + RuntimeError, + ) + pages = list(client.list_import_jobs(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_import_jobs_async_pager(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + resources.ImportJob(), + ], + next_page_token='abc', + ), + service.ListImportJobsResponse( + import_jobs=[], + next_page_token='def', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + ], + next_page_token='ghi', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_import_jobs(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, resources.ImportJob) + for i in responses) + + +@pytest.mark.asyncio +async def test_list_import_jobs_async_pages(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__', new_callable=mock.AsyncMock) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + resources.ImportJob(), + ], + next_page_token='abc', + ), + service.ListImportJobsResponse( + import_jobs=[], + next_page_token='def', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + ], + next_page_token='ghi', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_import_jobs(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + +@pytest.mark.parametrize("request_type", [ + service.GetKeyRingRequest, + dict, +]) +def test_get_key_ring(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing( + name='name_value', + ) + response = client.get_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetKeyRingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == 'name_value' + + +def test_get_key_ring_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetKeyRingRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_key_ring(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetKeyRingRequest( + name='name_value', + ) + +def test_get_key_ring_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_key_ring in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_key_ring] = mock_rpc + request = {} + client.get_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_key_ring(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_key_ring_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_key_ring in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_key_ring] = mock_rpc + + request = {} + await client.get_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_key_ring(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_key_ring_async(transport: str = 'grpc_asyncio', request_type=service.GetKeyRingRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( + name='name_value', + )) + response = await client.get_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetKeyRingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_get_key_ring_async_from_dict(): + await test_get_key_ring_async(request_type=dict) + +def test_get_key_ring_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetKeyRingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + call.return_value = resources.KeyRing() + client.get_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_key_ring_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetKeyRingRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) + await client.get_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_key_ring_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_key_ring( + 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_key_ring_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_key_ring( + service.GetKeyRingRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_key_ring_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_key_ring( + 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_key_ring_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_key_ring( + service.GetKeyRingRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.GetCryptoKeyRequest, + dict, +]) +def test_get_crypto_key(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + ) + response = client.get_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetCryptoKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +def test_get_crypto_key_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetCryptoKeyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_crypto_key(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetCryptoKeyRequest( + name='name_value', + ) + +def test_get_crypto_key_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_crypto_key in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_crypto_key] = mock_rpc + request = {} + client.get_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_crypto_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_crypto_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_crypto_key in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_crypto_key] = mock_rpc + + request = {} + await client.get_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_crypto_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.GetCryptoKeyRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + )) + response = await client.get_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetCryptoKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@pytest.mark.asyncio +async def test_get_crypto_key_async_from_dict(): + await test_get_crypto_key_async(request_type=dict) + +def test_get_crypto_key_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetCryptoKeyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.get_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crypto_key_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetCryptoKeyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + await client.get_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crypto_key_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_crypto_key( + 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_crypto_key_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_crypto_key( + service.GetCryptoKeyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_crypto_key_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_crypto_key( + 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_crypto_key_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_crypto_key( + service.GetCryptoKeyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.GetCryptoKeyVersionRequest, + dict, +]) +def test_get_crypto_key_version(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + response = client.get_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +def test_get_crypto_key_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetCryptoKeyVersionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_crypto_key_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetCryptoKeyVersionRequest( + name='name_value', + ) + +def test_get_crypto_key_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_crypto_key_version] = mock_rpc + request = {} + client.get_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_crypto_key_version in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_crypto_key_version] = mock_rpc + + request = {} + await client.get_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.GetCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + response = await client.get_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_get_crypto_key_version_async_from_dict(): + await test_get_crypto_key_version_async(request_type=dict) + +def test_get_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetCryptoKeyVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.get_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetCryptoKeyVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.get_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crypto_key_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_crypto_key_version( + 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_crypto_key_version_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_crypto_key_version( + service.GetCryptoKeyVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_crypto_key_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_crypto_key_version( + 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_crypto_key_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_crypto_key_version( + service.GetCryptoKeyVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.GetPublicKeyRequest, + dict, +]) +def test_get_public_key(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_public_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.PublicKey( + pem='pem_value', + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + name='name_value', + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.get_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetPublicKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.PublicKey) + assert response.pem == 'pem_value' + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.name == 'name_value' + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_get_public_key_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetPublicKeyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_public_key(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetPublicKeyRequest( + name='name_value', + ) + +def test_get_public_key_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_public_key in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_public_key] = mock_rpc + request = {} + client.get_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_public_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_public_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_public_key in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_public_key] = mock_rpc + + request = {} + await client.get_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_public_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_public_key_async(transport: str = 'grpc_asyncio', request_type=service.GetPublicKeyRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey( + pem='pem_value', + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + name='name_value', + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.get_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetPublicKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.PublicKey) + assert response.pem == 'pem_value' + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.name == 'name_value' + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_get_public_key_async_from_dict(): + await test_get_public_key_async(request_type=dict) + +def test_get_public_key_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetPublicKeyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + call.return_value = resources.PublicKey() + client.get_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_public_key_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetPublicKeyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey()) + await client.get_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_public_key_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.PublicKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_public_key( + 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_public_key_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_public_key( + service.GetPublicKeyRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_public_key_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.PublicKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_public_key( + 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_public_key_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_public_key( + service.GetPublicKeyRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.GetImportJobRequest, + dict, +]) +def test_get_import_job(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + ) + response = client.get_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetImportJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == 'name_value' + assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +def test_get_import_job_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetImportJobRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.get_import_job(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetImportJobRequest( + name='name_value', + ) + +def test_get_import_job_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_import_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_import_job] = mock_rpc + request = {} + client.get_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_import_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_import_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.get_import_job in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.get_import_job] = mock_rpc + + request = {} + await client.get_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_import_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_get_import_job_async(transport: str = 'grpc_asyncio', request_type=service.GetImportJobRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + )) + response = await client.get_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetImportJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == 'name_value' + assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +@pytest.mark.asyncio +async def test_get_import_job_async_from_dict(): + await test_get_import_job_async(request_type=dict) + +def test_get_import_job_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetImportJobRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + call.return_value = resources.ImportJob() + client.get_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_import_job_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetImportJobRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) + await client.get_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_import_job_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_import_job( + 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_import_job_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_import_job( + service.GetImportJobRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_get_import_job_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_import_job( + 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_import_job_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_import_job( + service.GetImportJobRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateKeyRingRequest, + dict, +]) +def test_create_key_ring(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing( + name='name_value', + ) + response = client.create_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.CreateKeyRingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == 'name_value' + + +def test_create_key_ring_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateKeyRingRequest( + parent='parent_value', + key_ring_id='key_ring_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_key_ring(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateKeyRingRequest( + parent='parent_value', + key_ring_id='key_ring_id_value', + ) + +def test_create_key_ring_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_key_ring in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_key_ring] = mock_rpc + request = {} + client.create_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_key_ring(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_key_ring_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_key_ring in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_key_ring] = mock_rpc + + request = {} + await client.create_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_key_ring(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_key_ring_async(transport: str = 'grpc_asyncio', request_type=service.CreateKeyRingRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( + name='name_value', + )) + response = await client.create_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.CreateKeyRingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == 'name_value' + + +@pytest.mark.asyncio +async def test_create_key_ring_async_from_dict(): + await test_create_key_ring_async(request_type=dict) + +def test_create_key_ring_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateKeyRingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + call.return_value = resources.KeyRing() + client.create_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_key_ring_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateKeyRingRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) + await client.create_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_key_ring_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_key_ring( + parent='parent_value', + key_ring_id='key_ring_id_value', + key_ring=resources.KeyRing(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].key_ring_id + mock_val = 'key_ring_id_value' + assert arg == mock_val + arg = args[0].key_ring + mock_val = resources.KeyRing(name='name_value') + assert arg == mock_val + + +def test_create_key_ring_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_key_ring( + service.CreateKeyRingRequest(), + parent='parent_value', + key_ring_id='key_ring_id_value', + key_ring=resources.KeyRing(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_key_ring_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.KeyRing() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_key_ring( + parent='parent_value', + key_ring_id='key_ring_id_value', + key_ring=resources.KeyRing(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].key_ring_id + mock_val = 'key_ring_id_value' + assert arg == mock_val + arg = args[0].key_ring + mock_val = resources.KeyRing(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_key_ring_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_key_ring( + service.CreateKeyRingRequest(), + parent='parent_value', + key_ring_id='key_ring_id_value', + key_ring=resources.KeyRing(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateCryptoKeyRequest, + dict, +]) +def test_create_crypto_key(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + ) + response = client.create_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.CreateCryptoKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +def test_create_crypto_key_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateCryptoKeyRequest( + parent='parent_value', + crypto_key_id='crypto_key_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_crypto_key(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateCryptoKeyRequest( + parent='parent_value', + crypto_key_id='crypto_key_id_value', + ) + +def test_create_crypto_key_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_crypto_key in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_crypto_key] = mock_rpc + request = {} + client.create_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_crypto_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_crypto_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_crypto_key in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_crypto_key] = mock_rpc + + request = {} + await client.create_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_crypto_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.CreateCryptoKeyRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + )) + response = await client.create_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.CreateCryptoKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@pytest.mark.asyncio +async def test_create_crypto_key_async_from_dict(): + await test_create_crypto_key_async(request_type=dict) + +def test_create_crypto_key_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateCryptoKeyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.create_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_crypto_key_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateCryptoKeyRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + await client.create_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_crypto_key_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_crypto_key( + parent='parent_value', + crypto_key_id='crypto_key_id_value', + crypto_key=resources.CryptoKey(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].crypto_key_id + mock_val = 'crypto_key_id_value' + assert arg == mock_val + arg = args[0].crypto_key + mock_val = resources.CryptoKey(name='name_value') + assert arg == mock_val + + +def test_create_crypto_key_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_crypto_key( + service.CreateCryptoKeyRequest(), + parent='parent_value', + crypto_key_id='crypto_key_id_value', + crypto_key=resources.CryptoKey(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_crypto_key_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_crypto_key( + parent='parent_value', + crypto_key_id='crypto_key_id_value', + crypto_key=resources.CryptoKey(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].crypto_key_id + mock_val = 'crypto_key_id_value' + assert arg == mock_val + arg = args[0].crypto_key + mock_val = resources.CryptoKey(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_crypto_key_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_crypto_key( + service.CreateCryptoKeyRequest(), + parent='parent_value', + crypto_key_id='crypto_key_id_value', + crypto_key=resources.CryptoKey(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + service.CreateCryptoKeyVersionRequest, + dict, +]) +def test_create_crypto_key_version(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + response = client.create_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.CreateCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +def test_create_crypto_key_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateCryptoKeyVersionRequest( + parent='parent_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_crypto_key_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateCryptoKeyVersionRequest( + parent='parent_value', + ) + +def test_create_crypto_key_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_crypto_key_version] = mock_rpc + request = {} + client.create_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_crypto_key_version in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_crypto_key_version] = mock_rpc + + request = {} + await client.create_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.CreateCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + response = await client.create_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.CreateCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_create_crypto_key_version_async_from_dict(): + await test_create_crypto_key_version_async(request_type=dict) + +def test_create_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateCryptoKeyVersionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.create_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateCryptoKeyVersionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.create_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_crypto_key_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_crypto_key_version( + parent='parent_value', + crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version + mock_val = resources.CryptoKeyVersion(name='name_value') + assert arg == mock_val + + +def test_create_crypto_key_version_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_crypto_key_version( + service.CreateCryptoKeyVersionRequest(), + parent='parent_value', + crypto_key_version=resources.CryptoKeyVersion(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_crypto_key_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_crypto_key_version( + parent='parent_value', + crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version + mock_val = resources.CryptoKeyVersion(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_crypto_key_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_crypto_key_version( + service.CreateCryptoKeyVersionRequest(), + parent='parent_value', + crypto_key_version=resources.CryptoKeyVersion(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + service.ImportCryptoKeyVersionRequest, + dict, +]) +def test_import_crypto_key_version(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + response = client.import_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ImportCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +def test_import_crypto_key_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ImportCryptoKeyVersionRequest( + parent='parent_value', + crypto_key_version='crypto_key_version_value', + import_job='import_job_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_crypto_key_version), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.import_crypto_key_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ImportCryptoKeyVersionRequest( + parent='parent_value', + crypto_key_version='crypto_key_version_value', + import_job='import_job_value', + ) + +def test_import_crypto_key_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.import_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_crypto_key_version] = mock_rpc + request = {} + client.import_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.import_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_import_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.import_crypto_key_version in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.import_crypto_key_version] = mock_rpc + + request = {} + await client.import_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.import_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_import_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.ImportCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + response = await client.import_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ImportCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_import_crypto_key_version_async_from_dict(): + await test_import_crypto_key_version_async(request_type=dict) + +def test_import_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ImportCryptoKeyVersionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.import_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_import_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ImportCryptoKeyVersionRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.import_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.import_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'parent=parent_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service.CreateImportJobRequest, + dict, +]) +def test_create_import_job(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + ) + response = client.create_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.CreateImportJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == 'name_value' + assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +def test_create_import_job_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateImportJobRequest( + parent='parent_value', + import_job_id='import_job_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.create_import_job(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateImportJobRequest( + parent='parent_value', + import_job_id='import_job_id_value', + ) + +def test_create_import_job_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_import_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_import_job] = mock_rpc + request = {} + client.create_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_import_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_import_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.create_import_job in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.create_import_job] = mock_rpc + + request = {} + await client.create_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.create_import_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_create_import_job_async(transport: str = 'grpc_asyncio', request_type=service.CreateImportJobRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + )) + response = await client.create_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.CreateImportJobRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == 'name_value' + assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +@pytest.mark.asyncio +async def test_create_import_job_async_from_dict(): + await test_create_import_job_async(request_type=dict) + +def test_create_import_job_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateImportJobRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + call.return_value = resources.ImportJob() + client.create_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.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_import_job_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateImportJobRequest() + + request.parent = 'parent_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) + await client.create_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.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_import_job_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_import_job( + parent='parent_value', + import_job_id='import_job_id_value', + import_job=resources.ImportJob(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].import_job_id + mock_val = 'import_job_id_value' + assert arg == mock_val + arg = args[0].import_job + mock_val = resources.ImportJob(name='name_value') + assert arg == mock_val + + +def test_create_import_job_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_import_job( + service.CreateImportJobRequest(), + parent='parent_value', + import_job_id='import_job_id_value', + import_job=resources.ImportJob(name='name_value'), + ) + +@pytest.mark.asyncio +async def test_create_import_job_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ImportJob() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_import_job( + parent='parent_value', + import_job_id='import_job_id_value', + import_job=resources.ImportJob(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].import_job_id + mock_val = 'import_job_id_value' + assert arg == mock_val + arg = args[0].import_job + mock_val = resources.ImportJob(name='name_value') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_create_import_job_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_import_job( + service.CreateImportJobRequest(), + parent='parent_value', + import_job_id='import_job_id_value', + import_job=resources.ImportJob(name='name_value'), + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateCryptoKeyRequest, + dict, +]) +def test_update_crypto_key(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + ) + response = client.update_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdateCryptoKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +def test_update_crypto_key_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateCryptoKeyRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_crypto_key(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyRequest( + ) + +def test_update_crypto_key_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_crypto_key in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_crypto_key] = mock_rpc + request = {} + client.update_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_crypto_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_crypto_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_crypto_key in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_crypto_key] = mock_rpc + + request = {} + await client.update_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_crypto_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + )) + response = await client.update_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdateCryptoKeyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@pytest.mark.asyncio +async def test_update_crypto_key_async_from_dict(): + await test_update_crypto_key_async(request_type=dict) + +def test_update_crypto_key_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyRequest() + + request.crypto_key.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.update_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'crypto_key.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_crypto_key_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyRequest() + + request.crypto_key.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + await client.update_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'crypto_key.name=name_value', + ) in kw['metadata'] + + +def test_update_crypto_key_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_crypto_key( + crypto_key=resources.CryptoKey(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].crypto_key + mock_val = resources.CryptoKey(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_crypto_key_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_crypto_key( + service.UpdateCryptoKeyRequest(), + crypto_key=resources.CryptoKey(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_crypto_key_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_crypto_key( + crypto_key=resources.CryptoKey(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].crypto_key + mock_val = resources.CryptoKey(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_crypto_key_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_crypto_key( + service.UpdateCryptoKeyRequest(), + crypto_key=resources.CryptoKey(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateCryptoKeyVersionRequest, + dict, +]) +def test_update_crypto_key_version(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + response = client.update_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdateCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +def test_update_crypto_key_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateCryptoKeyVersionRequest( + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_crypto_key_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyVersionRequest( + ) + +def test_update_crypto_key_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_crypto_key_version] = mock_rpc + request = {} + client.update_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_crypto_key_version in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_crypto_key_version] = mock_rpc + + request = {} + await client.update_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + response = await client.update_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdateCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_update_crypto_key_version_async_from_dict(): + await test_update_crypto_key_version_async(request_type=dict) + +def test_update_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyVersionRequest() + + request.crypto_key_version.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.update_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'crypto_key_version.name=name_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_update_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyVersionRequest() + + request.crypto_key_version.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.update_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'crypto_key_version.name=name_value', + ) in kw['metadata'] + + +def test_update_crypto_key_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_crypto_key_version( + crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version + mock_val = resources.CryptoKeyVersion(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_crypto_key_version_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_crypto_key_version( + service.UpdateCryptoKeyVersionRequest(), + crypto_key_version=resources.CryptoKeyVersion(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + +@pytest.mark.asyncio +async def test_update_crypto_key_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_crypto_key_version( + crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version + mock_val = resources.CryptoKeyVersion(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_crypto_key_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_crypto_key_version( + service.UpdateCryptoKeyVersionRequest(), + crypto_key_version=resources.CryptoKeyVersion(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateCryptoKeyPrimaryVersionRequest, + dict, +]) +def test_update_crypto_key_primary_version(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an 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_crypto_key_primary_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + ) + response = client.update_crypto_key_primary_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.UpdateCryptoKeyPrimaryVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +def test_update_crypto_key_primary_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.UpdateCryptoKeyPrimaryVersionRequest( + name='name_value', + crypto_key_version_id='crypto_key_version_id_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.update_crypto_key_primary_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateCryptoKeyPrimaryVersionRequest( + name='name_value', + crypto_key_version_id='crypto_key_version_id_value', + ) + +def test_update_crypto_key_primary_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_crypto_key_primary_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_crypto_key_primary_version] = mock_rpc + request = {} + client.update_crypto_key_primary_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_crypto_key_primary_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_crypto_key_primary_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.update_crypto_key_primary_version in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.update_crypto_key_primary_version] = mock_rpc + + request = {} + await client.update_crypto_key_primary_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.update_crypto_key_primary_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_update_crypto_key_primary_version_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyPrimaryVersionRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + )) + response = await client.update_crypto_key_primary_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.UpdateCryptoKeyPrimaryVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@pytest.mark.asyncio +async def test_update_crypto_key_primary_version_async_from_dict(): + await test_update_crypto_key_primary_version_async(request_type=dict) + +def test_update_crypto_key_primary_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyPrimaryVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.update_crypto_key_primary_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crypto_key_primary_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateCryptoKeyPrimaryVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + await client.update_crypto_key_primary_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_crypto_key_primary_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_crypto_key_primary_version( + name='name_value', + crypto_key_version_id='crypto_key_version_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].crypto_key_version_id + mock_val = 'crypto_key_version_id_value' + assert arg == mock_val + + +def test_update_crypto_key_primary_version_flattened_error(): + client = KeyManagementServiceClient( + credentials=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_crypto_key_primary_version( + service.UpdateCryptoKeyPrimaryVersionRequest(), + name='name_value', + crypto_key_version_id='crypto_key_version_id_value', + ) + +@pytest.mark.asyncio +async def test_update_crypto_key_primary_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKey() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_crypto_key_primary_version( + name='name_value', + crypto_key_version_id='crypto_key_version_id_value', + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = 'name_value' + assert arg == mock_val + arg = args[0].crypto_key_version_id + mock_val = 'crypto_key_version_id_value' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_update_crypto_key_primary_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_crypto_key_primary_version( + service.UpdateCryptoKeyPrimaryVersionRequest(), + name='name_value', + crypto_key_version_id='crypto_key_version_id_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.DestroyCryptoKeyVersionRequest, + dict, +]) +def test_destroy_crypto_key_version(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + response = client.destroy_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.DestroyCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +def test_destroy_crypto_key_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.DestroyCryptoKeyVersionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.destroy_crypto_key_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DestroyCryptoKeyVersionRequest( + name='name_value', + ) + +def test_destroy_crypto_key_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.destroy_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.destroy_crypto_key_version] = mock_rpc + request = {} + client.destroy_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.destroy_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_destroy_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.destroy_crypto_key_version in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.destroy_crypto_key_version] = mock_rpc + + request = {} + await client.destroy_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.destroy_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_destroy_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.DestroyCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + response = await client.destroy_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.DestroyCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_destroy_crypto_key_version_async_from_dict(): + await test_destroy_crypto_key_version_async(request_type=dict) + +def test_destroy_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DestroyCryptoKeyVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.destroy_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_destroy_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DestroyCryptoKeyVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.destroy_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_destroy_crypto_key_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.destroy_crypto_key_version( + 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_destroy_crypto_key_version_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.destroy_crypto_key_version( + service.DestroyCryptoKeyVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_destroy_crypto_key_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.destroy_crypto_key_version( + 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_destroy_crypto_key_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.destroy_crypto_key_version( + service.DestroyCryptoKeyVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.RestoreCryptoKeyVersionRequest, + dict, +]) +def test_restore_crypto_key_version(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + response = client.restore_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.RestoreCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +def test_restore_crypto_key_version_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.RestoreCryptoKeyVersionRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.restore_crypto_key_version(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.RestoreCryptoKeyVersionRequest( + name='name_value', + ) + +def test_restore_crypto_key_version_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.restore_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.restore_crypto_key_version] = mock_rpc + request = {} + client.restore_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.restore_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_restore_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.restore_crypto_key_version in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.restore_crypto_key_version] = mock_rpc + + request = {} + await client.restore_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.restore_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_restore_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.RestoreCryptoKeyVersionRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + response = await client.restore_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.RestoreCryptoKeyVersionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.asyncio +async def test_restore_crypto_key_version_async_from_dict(): + await test_restore_crypto_key_version_async(request_type=dict) + +def test_restore_crypto_key_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestoreCryptoKeyVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.restore_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_restore_crypto_key_version_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RestoreCryptoKeyVersionRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + await client.restore_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_restore_crypto_key_version_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.restore_crypto_key_version( + 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_restore_crypto_key_version_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_crypto_key_version( + service.RestoreCryptoKeyVersionRequest(), + name='name_value', + ) + +@pytest.mark.asyncio +async def test_restore_crypto_key_version_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = resources.CryptoKeyVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.restore_crypto_key_version( + 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_restore_crypto_key_version_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.restore_crypto_key_version( + service.RestoreCryptoKeyVersionRequest(), + name='name_value', + ) + + +@pytest.mark.parametrize("request_type", [ + service.EncryptRequest, + dict, +]) +def test_encrypt(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.EncryptResponse( + name='name_value', + ciphertext=b'ciphertext_blob', + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.EncryptRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.EncryptResponse) + assert response.name == 'name_value' + assert response.ciphertext == b'ciphertext_blob' + assert response.verified_plaintext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_encrypt_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.EncryptRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.encrypt(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.EncryptRequest( + name='name_value', + ) + +def test_encrypt_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.encrypt in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.encrypt] = mock_rpc + request = {} + client.encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.encrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_encrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.encrypt in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.encrypt] = mock_rpc + + request = {} + await client.encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.encrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_encrypt_async(transport: str = 'grpc_asyncio', request_type=service.EncryptRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse( + name='name_value', + ciphertext=b'ciphertext_blob', + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.EncryptRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.EncryptResponse) + assert response.name == 'name_value' + assert response.ciphertext == b'ciphertext_blob' + assert response.verified_plaintext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_encrypt_async_from_dict(): + await test_encrypt_async(request_type=dict) + +def test_encrypt_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.EncryptRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + call.return_value = service.EncryptResponse() + client.encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_encrypt_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.EncryptRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse()) + await client.encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_encrypt_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.EncryptResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.encrypt( + name='name_value', + plaintext=b'plaintext_blob', + ) + + # Establish that the 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].plaintext + mock_val = b'plaintext_blob' + assert arg == mock_val + + +def test_encrypt_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.encrypt( + service.EncryptRequest(), + name='name_value', + plaintext=b'plaintext_blob', + ) + +@pytest.mark.asyncio +async def test_encrypt_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.EncryptResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.encrypt( + name='name_value', + plaintext=b'plaintext_blob', + ) + + # Establish that 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].plaintext + mock_val = b'plaintext_blob' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_encrypt_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.encrypt( + service.EncryptRequest(), + name='name_value', + plaintext=b'plaintext_blob', + ) + + +@pytest.mark.parametrize("request_type", [ + service.DecryptRequest, + dict, +]) +def test_decrypt(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.DecryptResponse( + plaintext=b'plaintext_blob', + used_primary=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.DecryptRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.DecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.used_primary is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_decrypt_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.DecryptRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.decrypt(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DecryptRequest( + name='name_value', + ) + +def test_decrypt_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.decrypt in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.decrypt] = mock_rpc + request = {} + client.decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.decrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_decrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.decrypt in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.decrypt] = mock_rpc + + request = {} + await client.decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.decrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_decrypt_async(transport: str = 'grpc_asyncio', request_type=service.DecryptRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse( + plaintext=b'plaintext_blob', + used_primary=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.DecryptRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.DecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.used_primary is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_decrypt_async_from_dict(): + await test_decrypt_async(request_type=dict) + +def test_decrypt_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DecryptRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + call.return_value = service.DecryptResponse() + client.decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_decrypt_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DecryptRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse()) + await client.decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_decrypt_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.DecryptResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.decrypt( + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + # Establish that the 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].ciphertext + mock_val = b'ciphertext_blob' + assert arg == mock_val + + +def test_decrypt_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.decrypt( + service.DecryptRequest(), + name='name_value', + ciphertext=b'ciphertext_blob', + ) + +@pytest.mark.asyncio +async def test_decrypt_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.DecryptResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.decrypt( + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + # Establish that 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].ciphertext + mock_val = b'ciphertext_blob' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_decrypt_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.decrypt( + service.DecryptRequest(), + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + +@pytest.mark.parametrize("request_type", [ + service.RawEncryptRequest, + dict, +]) +def test_raw_encrypt(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.raw_encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.RawEncryptResponse( + ciphertext=b'ciphertext_blob', + initialization_vector=b'initialization_vector_blob', + tag_length=1053, + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, + name='name_value', + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.raw_encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.RawEncryptRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.RawEncryptResponse) + assert response.ciphertext == b'ciphertext_blob' + assert response.initialization_vector == b'initialization_vector_blob' + assert response.tag_length == 1053 + assert response.verified_plaintext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.verified_initialization_vector_crc32c is True + assert response.name == 'name_value' + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_raw_encrypt_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.RawEncryptRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.raw_encrypt), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.raw_encrypt(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.RawEncryptRequest( + name='name_value', + ) + +def test_raw_encrypt_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.raw_encrypt in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.raw_encrypt] = mock_rpc + request = {} + client.raw_encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.raw_encrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_raw_encrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.raw_encrypt in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.raw_encrypt] = mock_rpc + + request = {} + await client.raw_encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.raw_encrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_raw_encrypt_async(transport: str = 'grpc_asyncio', request_type=service.RawEncryptRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.raw_encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.RawEncryptResponse( + ciphertext=b'ciphertext_blob', + initialization_vector=b'initialization_vector_blob', + tag_length=1053, + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, + name='name_value', + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.raw_encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.RawEncryptRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.RawEncryptResponse) + assert response.ciphertext == b'ciphertext_blob' + assert response.initialization_vector == b'initialization_vector_blob' + assert response.tag_length == 1053 + assert response.verified_plaintext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.verified_initialization_vector_crc32c is True + assert response.name == 'name_value' + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_raw_encrypt_async_from_dict(): + await test_raw_encrypt_async(request_type=dict) + +def test_raw_encrypt_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RawEncryptRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.raw_encrypt), + '__call__') as call: + call.return_value = service.RawEncryptResponse() + client.raw_encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_raw_encrypt_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RawEncryptRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.raw_encrypt), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.RawEncryptResponse()) + await client.raw_encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service.RawDecryptRequest, + dict, +]) +def test_raw_decrypt(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.raw_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.RawDecryptResponse( + plaintext=b'plaintext_blob', + protection_level=resources.ProtectionLevel.SOFTWARE, + verified_ciphertext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, + ) + response = client.raw_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.RawDecryptRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.RawDecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.verified_ciphertext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.verified_initialization_vector_crc32c is True + + +def test_raw_decrypt_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.RawDecryptRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.raw_decrypt), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.raw_decrypt(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.RawDecryptRequest( + name='name_value', + ) + +def test_raw_decrypt_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.raw_decrypt in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.raw_decrypt] = mock_rpc + request = {} + client.raw_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.raw_decrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_raw_decrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.raw_decrypt in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.raw_decrypt] = mock_rpc + + request = {} + await client.raw_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.raw_decrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_raw_decrypt_async(transport: str = 'grpc_asyncio', request_type=service.RawDecryptRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.raw_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.RawDecryptResponse( + plaintext=b'plaintext_blob', + protection_level=resources.ProtectionLevel.SOFTWARE, + verified_ciphertext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, + )) + response = await client.raw_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.RawDecryptRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.RawDecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.verified_ciphertext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.verified_initialization_vector_crc32c is True + + +@pytest.mark.asyncio +async def test_raw_decrypt_async_from_dict(): + await test_raw_decrypt_async(request_type=dict) + +def test_raw_decrypt_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RawDecryptRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.raw_decrypt), + '__call__') as call: + call.return_value = service.RawDecryptResponse() + client.raw_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_raw_decrypt_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RawDecryptRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.raw_decrypt), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.RawDecryptResponse()) + await client.raw_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'name=name_value', + ) in kw['metadata'] + + +@pytest.mark.parametrize("request_type", [ + service.AsymmetricSignRequest, + dict, +]) +def test_asymmetric_sign(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricSignResponse( + signature=b'signature_blob', + verified_digest_crc32c=True, + name='name_value', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.asymmetric_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.AsymmetricSignRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricSignResponse) + assert response.signature == b'signature_blob' + assert response.verified_digest_crc32c is True + assert response.name == 'name_value' + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_asymmetric_sign_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.AsymmetricSignRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.asymmetric_sign(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.AsymmetricSignRequest( + name='name_value', + ) + +def test_asymmetric_sign_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.asymmetric_sign in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.asymmetric_sign] = mock_rpc + request = {} + client.asymmetric_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.asymmetric_sign(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_asymmetric_sign_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.asymmetric_sign in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.asymmetric_sign] = mock_rpc + + request = {} + await client.asymmetric_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.asymmetric_sign(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_asymmetric_sign_async(transport: str = 'grpc_asyncio', request_type=service.AsymmetricSignRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse( + signature=b'signature_blob', + verified_digest_crc32c=True, + name='name_value', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.asymmetric_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.AsymmetricSignRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricSignResponse) + assert response.signature == b'signature_blob' + assert response.verified_digest_crc32c is True + assert response.name == 'name_value' + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_asymmetric_sign_async_from_dict(): + await test_asymmetric_sign_async(request_type=dict) + +def test_asymmetric_sign_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AsymmetricSignRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + call.return_value = service.AsymmetricSignResponse() + client.asymmetric_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_asymmetric_sign_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AsymmetricSignRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse()) + await client.asymmetric_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_asymmetric_sign_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricSignResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.asymmetric_sign( + name='name_value', + digest=service.Digest(sha256=b'sha256_blob'), + ) + + # Establish that the 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].digest + mock_val = service.Digest(sha256=b'sha256_blob') + assert arg == mock_val + + +def test_asymmetric_sign_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.asymmetric_sign( + service.AsymmetricSignRequest(), + name='name_value', + digest=service.Digest(sha256=b'sha256_blob'), + ) + +@pytest.mark.asyncio +async def test_asymmetric_sign_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricSignResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.asymmetric_sign( + name='name_value', + digest=service.Digest(sha256=b'sha256_blob'), + ) + + # Establish that 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].digest + mock_val = service.Digest(sha256=b'sha256_blob') + assert arg == mock_val + +@pytest.mark.asyncio +async def test_asymmetric_sign_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.asymmetric_sign( + service.AsymmetricSignRequest(), + name='name_value', + digest=service.Digest(sha256=b'sha256_blob'), + ) + + +@pytest.mark.parametrize("request_type", [ + service.AsymmetricDecryptRequest, + dict, +]) +def test_asymmetric_decrypt(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricDecryptResponse( + plaintext=b'plaintext_blob', + verified_ciphertext_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.asymmetric_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.AsymmetricDecryptRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricDecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.verified_ciphertext_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_asymmetric_decrypt_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.AsymmetricDecryptRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.asymmetric_decrypt(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.AsymmetricDecryptRequest( + name='name_value', + ) + +def test_asymmetric_decrypt_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.asymmetric_decrypt in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.asymmetric_decrypt] = mock_rpc + request = {} + client.asymmetric_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.asymmetric_decrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_asymmetric_decrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.asymmetric_decrypt in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.asymmetric_decrypt] = mock_rpc + + request = {} + await client.asymmetric_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.asymmetric_decrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_asymmetric_decrypt_async(transport: str = 'grpc_asyncio', request_type=service.AsymmetricDecryptRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse( + plaintext=b'plaintext_blob', + verified_ciphertext_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.asymmetric_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.AsymmetricDecryptRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricDecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.verified_ciphertext_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_asymmetric_decrypt_async_from_dict(): + await test_asymmetric_decrypt_async(request_type=dict) + +def test_asymmetric_decrypt_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AsymmetricDecryptRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + call.return_value = service.AsymmetricDecryptResponse() + client.asymmetric_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_asymmetric_decrypt_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.AsymmetricDecryptRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse()) + await client.asymmetric_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_asymmetric_decrypt_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricDecryptResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.asymmetric_decrypt( + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + # Establish that the 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].ciphertext + mock_val = b'ciphertext_blob' + assert arg == mock_val + + +def test_asymmetric_decrypt_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.asymmetric_decrypt( + service.AsymmetricDecryptRequest(), + name='name_value', + ciphertext=b'ciphertext_blob', + ) + +@pytest.mark.asyncio +async def test_asymmetric_decrypt_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.AsymmetricDecryptResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.asymmetric_decrypt( + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + # Establish that 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].ciphertext + mock_val = b'ciphertext_blob' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_asymmetric_decrypt_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.asymmetric_decrypt( + service.AsymmetricDecryptRequest(), + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + +@pytest.mark.parametrize("request_type", [ + service.MacSignRequest, + dict, +]) +def test_mac_sign(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacSignResponse( + name='name_value', + mac=b'mac_blob', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.mac_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.MacSignRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacSignResponse) + assert response.name == 'name_value' + assert response.mac == b'mac_blob' + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_mac_sign_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.MacSignRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.mac_sign(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.MacSignRequest( + name='name_value', + ) + +def test_mac_sign_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.mac_sign in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.mac_sign] = mock_rpc + request = {} + client.mac_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.mac_sign(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_mac_sign_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.mac_sign in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.mac_sign] = mock_rpc + + request = {} + await client.mac_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.mac_sign(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_mac_sign_async(transport: str = 'grpc_asyncio', request_type=service.MacSignRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse( + name='name_value', + mac=b'mac_blob', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.mac_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.MacSignRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacSignResponse) + assert response.name == 'name_value' + assert response.mac == b'mac_blob' + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_mac_sign_async_from_dict(): + await test_mac_sign_async(request_type=dict) + +def test_mac_sign_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.MacSignRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + call.return_value = service.MacSignResponse() + client.mac_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_mac_sign_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.MacSignRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse()) + await client.mac_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_mac_sign_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacSignResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mac_sign( + name='name_value', + data=b'data_blob', + ) + + # Establish that the 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].data + mock_val = b'data_blob' + assert arg == mock_val + + +def test_mac_sign_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mac_sign( + service.MacSignRequest(), + name='name_value', + data=b'data_blob', + ) + +@pytest.mark.asyncio +async def test_mac_sign_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacSignResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mac_sign( + name='name_value', + data=b'data_blob', + ) + + # Establish that 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].data + mock_val = b'data_blob' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_mac_sign_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mac_sign( + service.MacSignRequest(), + name='name_value', + data=b'data_blob', + ) + + +@pytest.mark.parametrize("request_type", [ + service.MacVerifyRequest, + dict, +]) +def test_mac_verify(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacVerifyResponse( + name='name_value', + success=True, + verified_data_crc32c=True, + verified_mac_crc32c=True, + verified_success_integrity=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.mac_verify(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.MacVerifyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacVerifyResponse) + assert response.name == 'name_value' + assert response.success is True + assert response.verified_data_crc32c is True + assert response.verified_mac_crc32c is True + assert response.verified_success_integrity is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_mac_verify_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.MacVerifyRequest( + name='name_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.mac_verify(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.MacVerifyRequest( + name='name_value', + ) + +def test_mac_verify_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.mac_verify in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.mac_verify] = mock_rpc + request = {} + client.mac_verify(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.mac_verify(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_mac_verify_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.mac_verify in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.mac_verify] = mock_rpc + + request = {} + await client.mac_verify(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.mac_verify(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_mac_verify_async(transport: str = 'grpc_asyncio', request_type=service.MacVerifyRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse( + name='name_value', + success=True, + verified_data_crc32c=True, + verified_mac_crc32c=True, + verified_success_integrity=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + response = await client.mac_verify(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.MacVerifyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacVerifyResponse) + assert response.name == 'name_value' + assert response.success is True + assert response.verified_data_crc32c is True + assert response.verified_mac_crc32c is True + assert response.verified_success_integrity is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.asyncio +async def test_mac_verify_async_from_dict(): + await test_mac_verify_async(request_type=dict) + +def test_mac_verify_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.MacVerifyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + call.return_value = service.MacVerifyResponse() + client.mac_verify(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == 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_mac_verify_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.MacVerifyRequest() + + request.name = 'name_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse()) + await client.mac_verify(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == 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_mac_verify_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacVerifyResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mac_verify( + name='name_value', + data=b'data_blob', + mac=b'mac_blob', + ) + + # Establish that the 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].data + mock_val = b'data_blob' + assert arg == mock_val + arg = args[0].mac + mock_val = b'mac_blob' + assert arg == mock_val + + +def test_mac_verify_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mac_verify( + service.MacVerifyRequest(), + name='name_value', + data=b'data_blob', + mac=b'mac_blob', + ) + +@pytest.mark.asyncio +async def test_mac_verify_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacVerifyResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mac_verify( + name='name_value', + data=b'data_blob', + mac=b'mac_blob', + ) + + # Establish that 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].data + mock_val = b'data_blob' + assert arg == mock_val + arg = args[0].mac + mock_val = b'mac_blob' + assert arg == mock_val + +@pytest.mark.asyncio +async def test_mac_verify_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mac_verify( + service.MacVerifyRequest(), + name='name_value', + data=b'data_blob', + mac=b'mac_blob', + ) + + +@pytest.mark.parametrize("request_type", [ + service.GenerateRandomBytesRequest, + dict, +]) +def test_generate_random_bytes(request_type, transport: str = 'grpc'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateRandomBytesResponse( + data=b'data_blob', + ) + response = client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GenerateRandomBytesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateRandomBytesResponse) + assert response.data == b'data_blob' + + +def test_generate_random_bytes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='grpc', + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GenerateRandomBytesRequest( + location='location_value', + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client.generate_random_bytes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GenerateRandomBytesRequest( + location='location_value', + ) + +def test_generate_random_bytes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_random_bytes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_random_bytes] = mock_rpc + request = {} + client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_random_bytes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_random_bytes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._client._transport.generate_random_bytes in client._client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[client._client._transport.generate_random_bytes] = mock_rpc + + request = {} + await client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_random_bytes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + +@pytest.mark.asyncio +async def test_generate_random_bytes_async(transport: str = 'grpc_asyncio', request_type=service.GenerateRandomBytesRequest): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse( + data=b'data_blob', + )) + response = await client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GenerateRandomBytesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateRandomBytesResponse) + assert response.data == b'data_blob' + + +@pytest.mark.asyncio +async def test_generate_random_bytes_async_from_dict(): + await test_generate_random_bytes_async(request_type=dict) + +def test_generate_random_bytes_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateRandomBytesRequest() + + request.location = 'location_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + call.return_value = service.GenerateRandomBytesResponse() + client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'location=location_value', + ) in kw['metadata'] + + +@pytest.mark.asyncio +async def test_generate_random_bytes_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateRandomBytesRequest() + + request.location = 'location_value' + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse()) + await client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + 'x-goog-request-params', + 'location=location_value', + ) in kw['metadata'] + + +def test_generate_random_bytes_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateRandomBytesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_random_bytes( + location='location_value', + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].location + mock_val = 'location_value' + assert arg == mock_val + arg = args[0].length_bytes + mock_val = 1288 + assert arg == mock_val + arg = args[0].protection_level + mock_val = resources.ProtectionLevel.SOFTWARE + assert arg == mock_val + + +def test_generate_random_bytes_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_random_bytes( + service.GenerateRandomBytesRequest(), + location='location_value', + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + +@pytest.mark.asyncio +async def test_generate_random_bytes_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateRandomBytesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_random_bytes( + location='location_value', + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].location + mock_val = 'location_value' + assert arg == mock_val + arg = args[0].length_bytes + mock_val = 1288 + assert arg == mock_val + arg = args[0].protection_level + mock_val = resources.ProtectionLevel.SOFTWARE + assert arg == mock_val + +@pytest.mark.asyncio +async def test_generate_random_bytes_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.generate_random_bytes( + service.GenerateRandomBytesRequest(), + location='location_value', + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + +def test_list_key_rings_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_key_rings in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_key_rings] = mock_rpc + + request = {} + client.list_key_rings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_key_rings(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_key_rings_rest_required_fields(request_type=service.ListKeyRingsRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_key_rings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_key_rings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListKeyRingsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListKeyRingsResponse.pb(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_key_rings(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_key_rings_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_key_rings._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_key_rings_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListKeyRingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListKeyRingsResponse.pb(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_key_rings(**mock_args) + + # Establish that the underlying call 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/*}/keyRings" % client.transport._host, args[1]) + + +def test_list_key_rings_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_key_rings( + service.ListKeyRingsRequest(), + parent='parent_value', + ) + + +def test_list_key_rings_rest_pager(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + resources.KeyRing(), + ], + next_page_token='abc', + ), + service.ListKeyRingsResponse( + key_rings=[], + next_page_token='def', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + ], + next_page_token='ghi', + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListKeyRingsResponse.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_key_rings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.KeyRing) + for i in results) + + pages = list(client.list_key_rings(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_crypto_keys_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_crypto_keys in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_crypto_keys] = mock_rpc + + request = {} + client.list_crypto_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_crypto_keys(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_crypto_keys_rest_required_fields(request_type=service.ListCryptoKeysRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_crypto_keys._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_crypto_keys._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", "version_view", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeysResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListCryptoKeysResponse.pb(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_crypto_keys(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_crypto_keys_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_crypto_keys._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", "versionView", )) & set(("parent", ))) + + +def test_list_crypto_keys_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeysResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListCryptoKeysResponse.pb(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_crypto_keys(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate("%s/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys" % client.transport._host, args[1]) + + +def test_list_crypto_keys_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_crypto_keys( + service.ListCryptoKeysRequest(), + parent='parent_value', + ) + + +def test_list_crypto_keys_rest_pager(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + resources.CryptoKey(), + ], + next_page_token='abc', + ), + service.ListCryptoKeysResponse( + crypto_keys=[], + next_page_token='def', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListCryptoKeysResponse.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/keyRings/sample3'} + + pager = client.list_crypto_keys(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CryptoKey) + for i in results) + + pages = list(client.list_crypto_keys(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_crypto_key_versions_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_crypto_key_versions in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_crypto_key_versions] = mock_rpc + + request = {} + client.list_crypto_key_versions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_crypto_key_versions(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_crypto_key_versions_rest_required_fields(request_type=service.ListCryptoKeyVersionsRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_crypto_key_versions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_crypto_key_versions._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", "view", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeyVersionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListCryptoKeyVersionsResponse.pb(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_crypto_key_versions(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_crypto_key_versions_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_crypto_key_versions._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", "view", )) & set(("parent", ))) + + +def test_list_crypto_key_versions_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeyVersionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListCryptoKeyVersionsResponse.pb(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_crypto_key_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/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions" % client.transport._host, args[1]) + + +def test_list_crypto_key_versions_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_crypto_key_versions( + service.ListCryptoKeyVersionsRequest(), + parent='parent_value', + ) + + +def test_list_crypto_key_versions_rest_pager(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + next_page_token='abc', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[], + next_page_token='def', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + ], + next_page_token='ghi', + ), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListCryptoKeyVersionsResponse.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/keyRings/sample3/cryptoKeys/sample4'} + + pager = client.list_crypto_key_versions(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CryptoKeyVersion) + for i in results) + + pages = list(client.list_crypto_key_versions(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_list_import_jobs_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_import_jobs in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.list_import_jobs] = mock_rpc + + request = {} + client.list_import_jobs(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_import_jobs(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_import_jobs_rest_required_fields(request_type=service.ListImportJobsRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_import_jobs._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_import_jobs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListImportJobsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListImportJobsResponse.pb(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_import_jobs(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_list_import_jobs_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.list_import_jobs._get_unset_required_fields({}) + assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) + + +def test_list_import_jobs_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListImportJobsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListImportJobsResponse.pb(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_import_jobs(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*}/importJobs" % client.transport._host, args[1]) + + +def test_list_import_jobs_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_import_jobs( + service.ListImportJobsRequest(), + parent='parent_value', + ) + + +def test_list_import_jobs_rest_pager(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + #with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + resources.ImportJob(), + ], + next_page_token='abc', + ), + service.ListImportJobsResponse( + import_jobs=[], + next_page_token='def', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + ], + next_page_token='ghi', + ), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListImportJobsResponse.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/keyRings/sample3'} + + pager = client.list_import_jobs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.ImportJob) + for i in results) + + pages = list(client.list_import_jobs(request=sample_request).pages) + for page_, token in zip(pages, ['abc','def','ghi', '']): + assert page_.raw_page.next_page_token == token + + +def test_get_key_ring_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_key_ring in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_key_ring] = mock_rpc + + request = {} + client.get_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_key_ring(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_key_ring_rest_required_fields(request_type=service.GetKeyRingRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_key_ring._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_key_ring._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.KeyRing() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.KeyRing.pb(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_key_ring(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_key_ring_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_key_ring._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_key_ring_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.KeyRing() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.KeyRing.pb(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_key_ring(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*}" % client.transport._host, args[1]) + + +def test_get_key_ring_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_key_ring( + service.GetKeyRingRequest(), + name='name_value', + ) + + +def test_get_crypto_key_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_crypto_key in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_crypto_key] = mock_rpc + + request = {} + client.get_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_crypto_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_crypto_key_rest_required_fields(request_type=service.GetCryptoKeyRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_crypto_key._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_crypto_key._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(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_crypto_key(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_crypto_key_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_crypto_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_crypto_key_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(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_crypto_key(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*}" % client.transport._host, args[1]) + + +def test_get_crypto_key_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_crypto_key( + service.GetCryptoKeyRequest(), + name='name_value', + ) + + +def test_get_crypto_key_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_crypto_key_version] = mock_rpc + + request = {} + client.get_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_crypto_key_version_rest_required_fields(request_type=service.GetCryptoKeyVersionRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_crypto_key_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_crypto_key_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(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_crypto_key_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_crypto_key_version_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(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_crypto_key_version(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}" % client.transport._host, args[1]) + + +def test_get_crypto_key_version_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_crypto_key_version( + service.GetCryptoKeyVersionRequest(), + name='name_value', + ) + + +def test_get_public_key_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_public_key in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_public_key] = mock_rpc + + request = {} + client.get_public_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_public_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_public_key_rest_required_fields(request_type=service.GetPublicKeyRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_public_key._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_public_key._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.PublicKey() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.PublicKey.pb(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_public_key(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_public_key_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_public_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_public_key_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.PublicKey() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.PublicKey.pb(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_public_key(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}/publicKey" % client.transport._host, args[1]) + + +def test_get_public_key_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_public_key( + service.GetPublicKeyRequest(), + name='name_value', + ) + + +def test_get_import_job_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_import_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.get_import_job] = mock_rpc + + request = {} + client.get_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_import_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_import_job_rest_required_fields(request_type=service.GetImportJobRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_import_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_import_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ImportJob() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "get", + 'query_params': pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.ImportJob.pb(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_import_job(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_get_import_job_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.get_import_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_get_import_job_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.ImportJob() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/importJobs/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.ImportJob.pb(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_import_job(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/importJobs/*}" % client.transport._host, args[1]) + + +def test_get_import_job_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_import_job( + service.GetImportJobRequest(), + name='name_value', + ) + + +def test_create_key_ring_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_key_ring in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_key_ring] = mock_rpc + + request = {} + client.create_key_ring(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_key_ring(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_key_ring_rest_required_fields(request_type=service.CreateKeyRingRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["key_ring_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "keyRingId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_key_ring._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "keyRingId" in jsonified_request + assert jsonified_request["keyRingId"] == request_init["key_ring_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["keyRingId"] = 'key_ring_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_key_ring._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("key_ring_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "keyRingId" in jsonified_request + assert jsonified_request["keyRingId"] == 'key_ring_id_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.KeyRing() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.KeyRing.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_key_ring(request) + + expected_params = [ + ( + "keyRingId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_key_ring_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_key_ring._get_unset_required_fields({}) + assert set(unset_fields) == (set(("keyRingId", )) & set(("parent", "keyRingId", "keyRing", ))) + + +def test_create_key_ring_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.KeyRing() + + # 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', + key_ring_id='key_ring_id_value', + key_ring=resources.KeyRing(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.KeyRing.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_key_ring(**mock_args) + + # Establish that the underlying call 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/*}/keyRings" % client.transport._host, args[1]) + + +def test_create_key_ring_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_key_ring( + service.CreateKeyRingRequest(), + parent='parent_value', + key_ring_id='key_ring_id_value', + key_ring=resources.KeyRing(name='name_value'), + ) + + +def test_create_crypto_key_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_crypto_key in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_crypto_key] = mock_rpc + + request = {} + client.create_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_crypto_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_crypto_key_rest_required_fields(request_type=service.CreateCryptoKeyRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["crypto_key_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "cryptoKeyId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_crypto_key._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "cryptoKeyId" in jsonified_request + assert jsonified_request["cryptoKeyId"] == request_init["crypto_key_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["cryptoKeyId"] = 'crypto_key_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_crypto_key._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("crypto_key_id", "skip_initial_version_creation", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "cryptoKeyId" in jsonified_request + assert jsonified_request["cryptoKeyId"] == 'crypto_key_id_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_crypto_key(request) + + expected_params = [ + ( + "cryptoKeyId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_crypto_key_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_crypto_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(("cryptoKeyId", "skipInitialVersionCreation", )) & set(("parent", "cryptoKeyId", "cryptoKey", ))) + + +def test_create_crypto_key_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + crypto_key_id='crypto_key_id_value', + crypto_key=resources.CryptoKey(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_crypto_key(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*}/cryptoKeys" % client.transport._host, args[1]) + + +def test_create_crypto_key_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_crypto_key( + service.CreateCryptoKeyRequest(), + parent='parent_value', + crypto_key_id='crypto_key_id_value', + crypto_key=resources.CryptoKey(name='name_value'), + ) + + +def test_create_crypto_key_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_crypto_key_version] = mock_rpc + + request = {} + client.create_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_crypto_key_version_rest_required_fields(request_type=service.CreateCryptoKeyVersionRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_crypto_key_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_crypto_key_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_crypto_key_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "cryptoKeyVersion", ))) + + +def test_create_crypto_key_version_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + crypto_key_version=resources.CryptoKeyVersion(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_crypto_key_version(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions" % client.transport._host, args[1]) + + +def test_create_crypto_key_version_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_crypto_key_version( + service.CreateCryptoKeyVersionRequest(), + parent='parent_value', + crypto_key_version=resources.CryptoKeyVersion(name='name_value'), + ) + + +def test_import_crypto_key_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.import_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.import_crypto_key_version] = mock_rpc + + request = {} + client.import_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.import_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_import_crypto_key_version_rest_required_fields(request_type=service.ImportCryptoKeyVersionRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["import_job"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_crypto_key_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = 'parent_value' + jsonified_request["importJob"] = 'import_job_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_crypto_key_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "importJob" in jsonified_request + assert jsonified_request["importJob"] == 'import_job_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(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.import_crypto_key_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_import_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.import_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent", "algorithm", "importJob", ))) + + +def test_create_import_job_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_import_job in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.create_import_job] = mock_rpc + + request = {} + client.create_import_job(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_import_job(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_import_job_rest_required_fields(request_type=service.CreateImportJobRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["import_job_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + assert "importJobId" not in jsonified_request + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_import_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "importJobId" in jsonified_request + assert jsonified_request["importJobId"] == request_init["import_job_id"] + + jsonified_request["parent"] = 'parent_value' + jsonified_request["importJobId"] = 'import_job_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_import_job._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("import_job_id", )) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == 'parent_value' + assert "importJobId" in jsonified_request + assert jsonified_request["importJobId"] == 'import_job_id_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.ImportJob() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.ImportJob.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.create_import_job(request) + + expected_params = [ + ( + "importJobId", + "", + ), + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_create_import_job_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.create_import_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(("importJobId", )) & set(("parent", "importJobId", "importJob", ))) + + +def test_create_import_job_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.ImportJob() + + # get arguments that satisfy an http rule for this method + sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + + # get truthy value for each flattened field + mock_args = dict( + parent='parent_value', + import_job_id='import_job_id_value', + import_job=resources.ImportJob(name='name_value'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.ImportJob.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.create_import_job(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*}/importJobs" % client.transport._host, args[1]) + + +def test_create_import_job_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_import_job( + service.CreateImportJobRequest(), + parent='parent_value', + import_job_id='import_job_id_value', + import_job=resources.ImportJob(name='name_value'), + ) + + +def test_update_crypto_key_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_crypto_key in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_crypto_key] = mock_rpc + + request = {} + client.update_crypto_key(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_crypto_key(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_crypto_key_rest_required_fields(request_type=service.UpdateCryptoKeyRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_crypto_key._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_crypto_key._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + # 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 + + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_crypto_key(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_crypto_key_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_crypto_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("cryptoKey", "updateMask", ))) + + +def test_update_crypto_key_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + + # get arguments that satisfy an http rule for this method + sample_request = {'crypto_key': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'}} + + # get truthy value for each flattened field + mock_args = dict( + crypto_key=resources.CryptoKey(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 + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_crypto_key(**mock_args) + + # Establish that the underlying call 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/{crypto_key.name=projects/*/locations/*/keyRings/*/cryptoKeys/*}" % client.transport._host, args[1]) + + +def test_update_crypto_key_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_crypto_key( + service.UpdateCryptoKeyRequest(), + crypto_key=resources.CryptoKey(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_crypto_key_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_crypto_key_version] = mock_rpc + + request = {} + client.update_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_crypto_key_version_rest_required_fields(request_type=service.UpdateCryptoKeyVersionRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_crypto_key_version._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_crypto_key_version._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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # 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 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_crypto_key_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask", )) & set(("cryptoKeyVersion", "updateMask", ))) + + +def test_update_crypto_key_version_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {'crypto_key_version': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'}} + + # get truthy value for each flattened field + mock_args = dict( + crypto_key_version=resources.CryptoKeyVersion(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 + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_crypto_key_version(**mock_args) + + # Establish that the underlying call 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/{crypto_key_version.name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}" % client.transport._host, args[1]) + + +def test_update_crypto_key_version_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_crypto_key_version( + service.UpdateCryptoKeyVersionRequest(), + crypto_key_version=resources.CryptoKeyVersion(name='name_value'), + update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), + ) + + +def test_update_crypto_key_primary_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_crypto_key_primary_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.update_crypto_key_primary_version] = mock_rpc + + request = {} + client.update_crypto_key_primary_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_crypto_key_primary_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_crypto_key_primary_version_rest_required_fields(request_type=service.UpdateCryptoKeyPrimaryVersionRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["crypto_key_version_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_crypto_key_primary_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["cryptoKeyVersionId"] = 'crypto_key_version_id_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_crypto_key_primary_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "cryptoKeyVersionId" in jsonified_request + assert jsonified_request["cryptoKeyVersionId"] == 'crypto_key_version_id_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + response = client.update_crypto_key_primary_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_update_crypto_key_primary_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.update_crypto_key_primary_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "cryptoKeyVersionId", ))) + + +def test_update_crypto_key_primary_version_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + crypto_key_version_id='crypto_key_version_id_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode('UTF-8') + req.return_value = response_value + + client.update_crypto_key_primary_version(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*}:updatePrimaryVersion" % client.transport._host, args[1]) + + +def test_update_crypto_key_primary_version_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.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_crypto_key_primary_version( + service.UpdateCryptoKeyPrimaryVersionRequest(), + name='name_value', + crypto_key_version_id='crypto_key_version_id_value', + ) + + +def test_destroy_crypto_key_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.destroy_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.destroy_crypto_key_version] = mock_rpc + + request = {} + client.destroy_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.destroy_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_destroy_crypto_key_version_rest_required_fields(request_type=service.DestroyCryptoKeyVersionRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).destroy_crypto_key_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).destroy_crypto_key_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(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.destroy_crypto_key_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_destroy_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.destroy_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_destroy_crypto_key_version_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(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.destroy_crypto_key_version(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:destroy" % client.transport._host, args[1]) + + +def test_destroy_crypto_key_version_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.destroy_crypto_key_version( + service.DestroyCryptoKeyVersionRequest(), + name='name_value', + ) + + +def test_restore_crypto_key_version_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.restore_crypto_key_version in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.restore_crypto_key_version] = mock_rpc + + request = {} + client.restore_crypto_key_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.restore_crypto_key_version(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_restore_crypto_key_version_rest_required_fields(request_type=service.RestoreCryptoKeyVersionRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_crypto_key_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_crypto_key_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(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.restore_crypto_key_version(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_restore_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.restore_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_restore_crypto_key_version_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(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.restore_crypto_key_version(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:restore" % client.transport._host, args[1]) + + +def test_restore_crypto_key_version_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.restore_crypto_key_version( + service.RestoreCryptoKeyVersionRequest(), + name='name_value', + ) + + +def test_encrypt_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.encrypt in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.encrypt] = mock_rpc + + request = {} + client.encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.encrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_encrypt_rest_required_fields(request_type=service.EncryptRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["plaintext"] = b'' + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).encrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["plaintext"] = b'plaintext_blob' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).encrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "plaintext" in jsonified_request + assert jsonified_request["plaintext"] == b'plaintext_blob' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.EncryptResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.EncryptResponse.pb(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.encrypt(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_encrypt_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.encrypt._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "plaintext", ))) + + +def test_encrypt_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.EncryptResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + plaintext=b'plaintext_blob', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.EncryptResponse.pb(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.encrypt(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/**}:encrypt" % client.transport._host, args[1]) + + +def test_encrypt_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.encrypt( + service.EncryptRequest(), + name='name_value', + plaintext=b'plaintext_blob', + ) + + +def test_decrypt_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.decrypt in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.decrypt] = mock_rpc + + request = {} + client.decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.decrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_decrypt_rest_required_fields(request_type=service.DecryptRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["ciphertext"] = b'' + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).decrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["ciphertext"] = b'ciphertext_blob' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).decrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "ciphertext" in jsonified_request + assert jsonified_request["ciphertext"] == b'ciphertext_blob' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.DecryptResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.DecryptResponse.pb(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.decrypt(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_decrypt_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.decrypt._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "ciphertext", ))) + + +def test_decrypt_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.DecryptResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ciphertext=b'ciphertext_blob', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.DecryptResponse.pb(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.decrypt(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*}:decrypt" % client.transport._host, args[1]) + + +def test_decrypt_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.decrypt( + service.DecryptRequest(), + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + +def test_raw_encrypt_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.raw_encrypt in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.raw_encrypt] = mock_rpc + + request = {} + client.raw_encrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.raw_encrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_raw_encrypt_rest_required_fields(request_type=service.RawEncryptRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["plaintext"] = b'' + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).raw_encrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["plaintext"] = b'plaintext_blob' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).raw_encrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "plaintext" in jsonified_request + assert jsonified_request["plaintext"] == b'plaintext_blob' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.RawEncryptResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.RawEncryptResponse.pb(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.raw_encrypt(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_raw_encrypt_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.raw_encrypt._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "plaintext", ))) + + +def test_raw_decrypt_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.raw_decrypt in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.raw_decrypt] = mock_rpc + + request = {} + client.raw_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.raw_decrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_raw_decrypt_rest_required_fields(request_type=service.RawDecryptRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["ciphertext"] = b'' + request_init["initialization_vector"] = b'' + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).raw_decrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["ciphertext"] = b'ciphertext_blob' + jsonified_request["initializationVector"] = b'initialization_vector_blob' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).raw_decrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "ciphertext" in jsonified_request + assert jsonified_request["ciphertext"] == b'ciphertext_blob' + assert "initializationVector" in jsonified_request + assert jsonified_request["initializationVector"] == b'initialization_vector_blob' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.RawDecryptResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.RawDecryptResponse.pb(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.raw_decrypt(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_raw_decrypt_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.raw_decrypt._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "ciphertext", "initializationVector", ))) + + +def test_asymmetric_sign_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.asymmetric_sign in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.asymmetric_sign] = mock_rpc + + request = {} + client.asymmetric_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.asymmetric_sign(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_asymmetric_sign_rest_required_fields(request_type=service.AsymmetricSignRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).asymmetric_sign._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).asymmetric_sign._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricSignResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.AsymmetricSignResponse.pb(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.asymmetric_sign(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_asymmetric_sign_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.asymmetric_sign._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", ))) + + +def test_asymmetric_sign_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricSignResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + digest=service.Digest(sha256=b'sha256_blob'), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.AsymmetricSignResponse.pb(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.asymmetric_sign(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricSign" % client.transport._host, args[1]) + + +def test_asymmetric_sign_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.asymmetric_sign( + service.AsymmetricSignRequest(), + name='name_value', + digest=service.Digest(sha256=b'sha256_blob'), + ) + + +def test_asymmetric_decrypt_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.asymmetric_decrypt in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.asymmetric_decrypt] = mock_rpc + + request = {} + client.asymmetric_decrypt(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.asymmetric_decrypt(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_asymmetric_decrypt_rest_required_fields(request_type=service.AsymmetricDecryptRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["ciphertext"] = b'' + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).asymmetric_decrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["ciphertext"] = b'ciphertext_blob' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).asymmetric_decrypt._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "ciphertext" in jsonified_request + assert jsonified_request["ciphertext"] == b'ciphertext_blob' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricDecryptResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.AsymmetricDecryptResponse.pb(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.asymmetric_decrypt(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_asymmetric_decrypt_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.asymmetric_decrypt._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "ciphertext", ))) + + +def test_asymmetric_decrypt_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricDecryptResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + ciphertext=b'ciphertext_blob', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.AsymmetricDecryptResponse.pb(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.asymmetric_decrypt(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricDecrypt" % client.transport._host, args[1]) + + +def test_asymmetric_decrypt_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.asymmetric_decrypt( + service.AsymmetricDecryptRequest(), + name='name_value', + ciphertext=b'ciphertext_blob', + ) + + +def test_mac_sign_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.mac_sign in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.mac_sign] = mock_rpc + + request = {} + client.mac_sign(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.mac_sign(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_mac_sign_rest_required_fields(request_type=service.MacSignRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["data"] = b'' + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).mac_sign._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["data"] = b'data_blob' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).mac_sign._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "data" in jsonified_request + assert jsonified_request["data"] == b'data_blob' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.MacSignResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.MacSignResponse.pb(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.mac_sign(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_mac_sign_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.mac_sign._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "data", ))) + + +def test_mac_sign_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.MacSignResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + data=b'data_blob', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.MacSignResponse.pb(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.mac_sign(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macSign" % client.transport._host, args[1]) + + +def test_mac_sign_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mac_sign( + service.MacSignRequest(), + name='name_value', + data=b'data_blob', + ) + + +def test_mac_verify_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.mac_verify in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.mac_verify] = mock_rpc + + request = {} + client.mac_verify(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.mac_verify(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_mac_verify_rest_required_fields(request_type=service.MacVerifyRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["name"] = "" + request_init["data"] = b'' + request_init["mac"] = b'' + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads(json_format.MessageToJson( + pb_request, + use_integers_for_enums=False + )) + + # verify fields with default values are dropped + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).mac_verify._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = 'name_value' + jsonified_request["data"] = b'data_blob' + jsonified_request["mac"] = b'mac_blob' + + unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).mac_verify._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == 'name_value' + assert "data" in jsonified_request + assert jsonified_request["data"] == b'data_blob' + assert "mac" in jsonified_request + assert jsonified_request["mac"] == b'mac_blob' + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport='rest', + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.MacVerifyResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, 'transcode') as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + 'uri': 'v1/sample_method', + 'method': "post", + 'query_params': pb_request, + } + transcode_result['body'] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.MacVerifyResponse.pb(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.mac_verify(request) + + expected_params = [ + ('$alt', 'json;enum-encoding=int') + ] + actual_params = req.call_args.kwargs['params'] + assert expected_params == actual_params + + +def test_mac_verify_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) + + unset_fields = transport.mac_verify._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name", "data", "mac", ))) + + +def test_mac_verify_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.MacVerifyResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + + # get truthy value for each flattened field + mock_args = dict( + name='name_value', + data=b'data_blob', + mac=b'mac_blob', + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.MacVerifyResponse.pb(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.mac_verify(**mock_args) + + # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macVerify" % client.transport._host, args[1]) + + +def test_mac_verify_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mac_verify( + service.MacVerifyRequest(), + name='name_value', + data=b'data_blob', + mac=b'mac_blob', + ) + + +def test_generate_random_bytes_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.generate_random_bytes in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. + client._transport._wrapped_methods[client._transport.generate_random_bytes] = mock_rpc + + request = {} + client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_random_bytes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_generate_random_bytes_rest_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.GenerateRandomBytesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {'location': 'projects/sample1/locations/sample2'} + + # get truthy value for each flattened field + mock_args = dict( + location='location_value', + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.GenerateRandomBytesResponse.pb(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.generate_random_bytes(**mock_args) + + # Establish that the underlying call 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/{location=projects/*/locations/*}:generateRandomBytes" % client.transport._host, args[1]) + + +def test_generate_random_bytes_rest_flattened_error(transport: str = 'rest'): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_random_bytes( + service.GenerateRandomBytesRequest(), + location='location_value', + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + client_options=options, + credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = KeyManagementServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = KeyManagementServiceClient(transport=transport) + assert client.transport is transport + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.KeyManagementServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.KeyManagementServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + +@pytest.mark.parametrize("transport_class", [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, + transports.KeyManagementServiceRestTransport, +]) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + +def test_transport_kind_grpc(): + transport = KeyManagementServiceClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_key_rings_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + call.return_value = service.ListKeyRingsResponse() + client.list_key_rings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListKeyRingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_crypto_keys_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + call.return_value = service.ListCryptoKeysResponse() + client.list_crypto_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCryptoKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_crypto_key_versions_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + call.return_value = service.ListCryptoKeyVersionsResponse() + client.list_crypto_key_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCryptoKeyVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_import_jobs_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + call.return_value = service.ListImportJobsResponse() + client.list_import_jobs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListImportJobsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_key_ring_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + call.return_value = resources.KeyRing() + client.get_key_ring(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetKeyRingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_crypto_key_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.get_crypto_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCryptoKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_crypto_key_version_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.get_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_public_key_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + call.return_value = resources.PublicKey() + client.get_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetPublicKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_import_job_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + call.return_value = resources.ImportJob() + client.get_import_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetImportJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_key_ring_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + call.return_value = resources.KeyRing() + client.create_key_ring(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateKeyRingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_crypto_key_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.create_crypto_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCryptoKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_crypto_key_version_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.create_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_crypto_key_version_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.import_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ImportCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_import_job_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + call.return_value = resources.ImportJob() + client.create_import_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateImportJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_crypto_key_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.update_crypto_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCryptoKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_crypto_key_version_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.update_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_crypto_key_primary_version_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + call.return_value = resources.CryptoKey() + client.update_crypto_key_primary_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCryptoKeyPrimaryVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_destroy_crypto_key_version_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.destroy_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DestroyCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_crypto_key_version_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + call.return_value = resources.CryptoKeyVersion() + client.restore_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RestoreCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_encrypt_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + call.return_value = service.EncryptResponse() + client.encrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EncryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_decrypt_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + call.return_value = service.DecryptResponse() + client.decrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DecryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_raw_encrypt_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.raw_encrypt), + '__call__') as call: + call.return_value = service.RawEncryptResponse() + client.raw_encrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RawEncryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_raw_decrypt_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.raw_decrypt), + '__call__') as call: + call.return_value = service.RawDecryptResponse() + client.raw_decrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RawDecryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_asymmetric_sign_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + call.return_value = service.AsymmetricSignResponse() + client.asymmetric_sign(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AsymmetricSignRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_asymmetric_decrypt_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + call.return_value = service.AsymmetricDecryptResponse() + client.asymmetric_decrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AsymmetricDecryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mac_sign_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + call.return_value = service.MacSignResponse() + client.mac_sign(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.MacSignRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mac_verify_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + call.return_value = service.MacVerifyResponse() + client.mac_verify(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.MacVerifyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_random_bytes_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + call.return_value = service.GenerateRandomBytesResponse() + client.generate_random_bytes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GenerateRandomBytesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = KeyManagementServiceAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_key_rings_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_key_rings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListKeyRingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_crypto_keys_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_crypto_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCryptoKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_crypto_key_versions_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_crypto_key_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCryptoKeyVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_list_import_jobs_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse( + next_page_token='next_page_token_value', + total_size=1086, + )) + await client.list_import_jobs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListImportJobsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_key_ring_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( + name='name_value', + )) + await client.get_key_ring(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetKeyRingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_crypto_key_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + )) + await client.get_crypto_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCryptoKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_crypto_key_version_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + await client.get_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_public_key_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey( + pem='pem_value', + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + name='name_value', + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + await client.get_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetPublicKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_get_import_job_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + )) + await client.get_import_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetImportJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_key_ring_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( + name='name_value', + )) + await client.create_key_ring(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateKeyRingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_crypto_key_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + )) + await client.create_crypto_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCryptoKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_crypto_key_version_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + await client.create_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_import_crypto_key_version_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + await client.import_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ImportCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_create_import_job_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + )) + await client.create_import_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateImportJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_crypto_key_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + )) + await client.update_crypto_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCryptoKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_crypto_key_version_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + await client.update_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_update_crypto_key_primary_version_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + )) + await client.update_crypto_key_primary_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCryptoKeyPrimaryVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_destroy_crypto_key_version_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + await client.destroy_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DestroyCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_restore_crypto_key_version_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + )) + await client.restore_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RestoreCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_encrypt_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse( + name='name_value', + ciphertext=b'ciphertext_blob', + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + await client.encrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EncryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_decrypt_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse( + plaintext=b'plaintext_blob', + used_primary=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + await client.decrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DecryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_raw_encrypt_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.raw_encrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.RawEncryptResponse( + ciphertext=b'ciphertext_blob', + initialization_vector=b'initialization_vector_blob', + tag_length=1053, + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, + name='name_value', + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + await client.raw_encrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RawEncryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_raw_decrypt_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.raw_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.RawDecryptResponse( + plaintext=b'plaintext_blob', + protection_level=resources.ProtectionLevel.SOFTWARE, + verified_ciphertext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, + )) + await client.raw_decrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RawDecryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_asymmetric_sign_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse( + signature=b'signature_blob', + verified_digest_crc32c=True, + name='name_value', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + await client.asymmetric_sign(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AsymmetricSignRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_asymmetric_decrypt_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse( + plaintext=b'plaintext_blob', + verified_ciphertext_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + await client.asymmetric_decrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AsymmetricDecryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mac_sign_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse( + name='name_value', + mac=b'mac_blob', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + await client.mac_sign(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.MacSignRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_mac_verify_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse( + name='name_value', + success=True, + verified_data_crc32c=True, + verified_mac_crc32c=True, + verified_success_integrity=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + )) + await client.mac_verify(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.MacVerifyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_generate_random_bytes_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse( + data=b'data_blob', + )) + await client.generate_random_bytes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GenerateRandomBytesRequest() + + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = KeyManagementServiceClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_key_rings_rest_bad_request(request_type=service.ListKeyRingsRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_key_rings(request) + + +@pytest.mark.parametrize("request_type", [ + service.ListKeyRingsRequest, + dict, +]) +def test_list_key_rings_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListKeyRingsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListKeyRingsResponse.pb(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_key_rings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListKeyRingsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_key_rings_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_list_key_rings") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_list_key_rings") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListKeyRingsRequest.pb(service.ListKeyRingsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListKeyRingsResponse.to_json(service.ListKeyRingsResponse()) + req.return_value.content = return_value + + request = service.ListKeyRingsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListKeyRingsResponse() + + client.list_key_rings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_crypto_keys_rest_bad_request(request_type=service.ListCryptoKeysRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_crypto_keys(request) + + +@pytest.mark.parametrize("request_type", [ + service.ListCryptoKeysRequest, + dict, +]) +def test_list_crypto_keys_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeysResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListCryptoKeysResponse.pb(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_crypto_keys(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeysPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_crypto_keys_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_list_crypto_keys") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_list_crypto_keys") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCryptoKeysRequest.pb(service.ListCryptoKeysRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListCryptoKeysResponse.to_json(service.ListCryptoKeysResponse()) + req.return_value.content = return_value + + request = service.ListCryptoKeysRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCryptoKeysResponse() + + client.list_crypto_keys(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_crypto_key_versions_rest_bad_request(request_type=service.ListCryptoKeyVersionsRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_crypto_key_versions(request) + + +@pytest.mark.parametrize("request_type", [ + service.ListCryptoKeyVersionsRequest, + dict, +]) +def test_list_crypto_key_versions_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeyVersionsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListCryptoKeyVersionsResponse.pb(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_crypto_key_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCryptoKeyVersionsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_crypto_key_versions_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_list_crypto_key_versions") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_list_crypto_key_versions") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListCryptoKeyVersionsRequest.pb(service.ListCryptoKeyVersionsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListCryptoKeyVersionsResponse.to_json(service.ListCryptoKeyVersionsResponse()) + req.return_value.content = return_value + + request = service.ListCryptoKeyVersionsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListCryptoKeyVersionsResponse() + + client.list_crypto_key_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_import_jobs_rest_bad_request(request_type=service.ListImportJobsRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_import_jobs(request) + + +@pytest.mark.parametrize("request_type", [ + service.ListImportJobsRequest, + dict, +]) +def test_list_import_jobs_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.ListImportJobsResponse( + next_page_token='next_page_token_value', + total_size=1086, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListImportJobsResponse.pb(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_import_jobs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListImportJobsPager) + assert response.next_page_token == 'next_page_token_value' + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_import_jobs_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_list_import_jobs") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_list_import_jobs") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListImportJobsRequest.pb(service.ListImportJobsRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListImportJobsResponse.to_json(service.ListImportJobsResponse()) + req.return_value.content = return_value + + request = service.ListImportJobsRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListImportJobsResponse() + + client.list_import_jobs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_key_ring_rest_bad_request(request_type=service.GetKeyRingRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_key_ring(request) + + +@pytest.mark.parametrize("request_type", [ + service.GetKeyRingRequest, + dict, +]) +def test_get_key_ring_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.KeyRing( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.KeyRing.pb(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_key_ring(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_key_ring_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_get_key_ring") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_get_key_ring") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetKeyRingRequest.pb(service.GetKeyRingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.KeyRing.to_json(resources.KeyRing()) + req.return_value.content = return_value + + request = service.GetKeyRingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.KeyRing() + + client.get_key_ring(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_crypto_key_rest_bad_request(request_type=service.GetCryptoKeyRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_crypto_key(request) + + +@pytest.mark.parametrize("request_type", [ + service.GetCryptoKeyRequest, + dict, +]) +def test_get_crypto_key_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(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_crypto_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_crypto_key_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_get_crypto_key") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_get_crypto_key") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCryptoKeyRequest.pb(service.GetCryptoKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CryptoKey.to_json(resources.CryptoKey()) + req.return_value.content = return_value + + request = service.GetCryptoKeyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKey() + + client.get_crypto_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_crypto_key_version_rest_bad_request(request_type=service.GetCryptoKeyVersionRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_crypto_key_version(request) + + +@pytest.mark.parametrize("request_type", [ + service.GetCryptoKeyVersionRequest, + dict, +]) +def test_get_crypto_key_version_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(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_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_get_crypto_key_version") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_get_crypto_key_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetCryptoKeyVersionRequest.pb(service.GetCryptoKeyVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) + req.return_value.content = return_value + + request = service.GetCryptoKeyVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.get_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_public_key_rest_bad_request(request_type=service.GetPublicKeyRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_public_key(request) + + +@pytest.mark.parametrize("request_type", [ + service.GetPublicKeyRequest, + dict, +]) +def test_get_public_key_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.PublicKey( + pem='pem_value', + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + name='name_value', + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.PublicKey.pb(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_public_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.PublicKey) + assert response.pem == 'pem_value' + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.name == 'name_value' + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_public_key_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_get_public_key") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_get_public_key") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetPublicKeyRequest.pb(service.GetPublicKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.PublicKey.to_json(resources.PublicKey()) + req.return_value.content = return_value + + request = service.GetPublicKeyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.PublicKey() + + client.get_public_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_import_job_rest_bad_request(request_type=service.GetImportJobRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/importJobs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.get_import_job(request) + + +@pytest.mark.parametrize("request_type", [ + service.GetImportJobRequest, + dict, +]) +def test_get_import_job_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/importJobs/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.ImportJob.pb(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_import_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == 'name_value' + assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_import_job_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_get_import_job") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_get_import_job") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetImportJobRequest.pb(service.GetImportJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.ImportJob.to_json(resources.ImportJob()) + req.return_value.content = return_value + + request = service.GetImportJobRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ImportJob() + + client.get_import_job(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_key_ring_rest_bad_request(request_type=service.CreateKeyRingRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_key_ring(request) + + +@pytest.mark.parametrize("request_type", [ + service.CreateKeyRingRequest, + dict, +]) +def test_create_key_ring_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2'} + request_init["key_ring"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateKeyRingRequest.meta.fields["key_ring"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["key_ring"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["key_ring"][field])): + del request_init["key_ring"][field][i][subfield] + else: + del request_init["key_ring"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.KeyRing( + name='name_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.KeyRing.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_key_ring(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.KeyRing) + assert response.name == 'name_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_key_ring_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_create_key_ring") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_create_key_ring") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateKeyRingRequest.pb(service.CreateKeyRingRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.KeyRing.to_json(resources.KeyRing()) + req.return_value.content = return_value + + request = service.CreateKeyRingRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.KeyRing() + + client.create_key_ring(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_crypto_key_rest_bad_request(request_type=service.CreateCryptoKeyRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_crypto_key(request) + + +@pytest.mark.parametrize("request_type", [ + service.CreateCryptoKeyRequest, + dict, +]) +def test_create_crypto_key_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + request_init["crypto_key"] = {'name': 'name_value', 'primary': {'name': 'name_value', 'state': 5, 'protection_level': 1, 'algorithm': 1, 'attestation': {'format_': 3, 'content': b'content_blob', 'cert_chains': {'cavium_certs': ['cavium_certs_value1', 'cavium_certs_value2'], 'google_card_certs': ['google_card_certs_value1', 'google_card_certs_value2'], 'google_partition_certs': ['google_partition_certs_value1', 'google_partition_certs_value2']}}, 'create_time': {'seconds': 751, 'nanos': 543}, 'generate_time': {}, 'destroy_time': {}, 'destroy_event_time': {}, 'import_job': 'import_job_value', 'import_time': {}, 'import_failure_reason': 'import_failure_reason_value', 'generation_failure_reason': 'generation_failure_reason_value', 'external_destruction_failure_reason': 'external_destruction_failure_reason_value', 'external_protection_level_options': {'external_key_uri': 'external_key_uri_value', 'ekm_connection_key_path': 'ekm_connection_key_path_value'}, 'reimport_eligible': True}, 'purpose': 1, 'create_time': {}, 'next_rotation_time': {}, 'rotation_period': {'seconds': 751, 'nanos': 543}, 'version_template': {'protection_level': 1, 'algorithm': 1}, 'labels': {}, 'import_only': True, 'destroy_scheduled_duration': {}, 'crypto_key_backend': 'crypto_key_backend_value', 'key_access_justifications_policy': {'allowed_access_reasons': [1]}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateCryptoKeyRequest.meta.fields["crypto_key"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["crypto_key"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["crypto_key"][field])): + del request_init["crypto_key"][field][i][subfield] + else: + del request_init["crypto_key"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_crypto_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_crypto_key_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_create_crypto_key") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_create_crypto_key") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCryptoKeyRequest.pb(service.CreateCryptoKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CryptoKey.to_json(resources.CryptoKey()) + req.return_value.content = return_value + + request = service.CreateCryptoKeyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKey() + + client.create_crypto_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_crypto_key_version_rest_bad_request(request_type=service.CreateCryptoKeyVersionRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_crypto_key_version(request) + + +@pytest.mark.parametrize("request_type", [ + service.CreateCryptoKeyVersionRequest, + dict, +]) +def test_create_crypto_key_version_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request_init["crypto_key_version"] = {'name': 'name_value', 'state': 5, 'protection_level': 1, 'algorithm': 1, 'attestation': {'format_': 3, 'content': b'content_blob', 'cert_chains': {'cavium_certs': ['cavium_certs_value1', 'cavium_certs_value2'], 'google_card_certs': ['google_card_certs_value1', 'google_card_certs_value2'], 'google_partition_certs': ['google_partition_certs_value1', 'google_partition_certs_value2']}}, 'create_time': {'seconds': 751, 'nanos': 543}, 'generate_time': {}, 'destroy_time': {}, 'destroy_event_time': {}, 'import_job': 'import_job_value', 'import_time': {}, 'import_failure_reason': 'import_failure_reason_value', 'generation_failure_reason': 'generation_failure_reason_value', 'external_destruction_failure_reason': 'external_destruction_failure_reason_value', 'external_protection_level_options': {'external_key_uri': 'external_key_uri_value', 'ekm_connection_key_path': 'ekm_connection_key_path_value'}, 'reimport_eligible': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateCryptoKeyVersionRequest.meta.fields["crypto_key_version"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["crypto_key_version"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["crypto_key_version"][field])): + del request_init["crypto_key_version"][field][i][subfield] + else: + del request_init["crypto_key_version"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_create_crypto_key_version") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_create_crypto_key_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateCryptoKeyVersionRequest.pb(service.CreateCryptoKeyVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) + req.return_value.content = return_value + + request = service.CreateCryptoKeyVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.create_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_import_crypto_key_version_rest_bad_request(request_type=service.ImportCryptoKeyVersionRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.import_crypto_key_version(request) + + +@pytest.mark.parametrize("request_type", [ + service.ImportCryptoKeyVersionRequest, + dict, +]) +def test_import_crypto_key_version_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(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.import_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_import_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_import_crypto_key_version") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_import_crypto_key_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ImportCryptoKeyVersionRequest.pb(service.ImportCryptoKeyVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) + req.return_value.content = return_value + + request = service.ImportCryptoKeyVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.import_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_import_job_rest_bad_request(request_type=service.CreateImportJobRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.create_import_job(request) + + +@pytest.mark.parametrize("request_type", [ + service.CreateImportJobRequest, + dict, +]) +def test_create_import_job_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} + request_init["import_job"] = {'name': 'name_value', 'import_method': 1, 'protection_level': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'generate_time': {}, 'expire_time': {}, 'expire_event_time': {}, 'state': 1, 'public_key': {'pem': 'pem_value'}, 'attestation': {'format_': 3, 'content': b'content_blob', 'cert_chains': {'cavium_certs': ['cavium_certs_value1', 'cavium_certs_value2'], 'google_card_certs': ['google_card_certs_value1', 'google_card_certs_value2'], 'google_partition_certs': ['google_partition_certs_value1', 'google_partition_certs_value2']}}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.CreateImportJobRequest.meta.fields["import_job"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["import_job"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["import_job"][field])): + del request_init["import_job"][field][i][subfield] + else: + del request_init["import_job"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.ImportJob( + name='name_value', + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + protection_level=resources.ProtectionLevel.SOFTWARE, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.ImportJob.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.create_import_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ImportJob) + assert response.name == 'name_value' + assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_import_job_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_create_import_job") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_create_import_job") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.CreateImportJobRequest.pb(service.CreateImportJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.ImportJob.to_json(resources.ImportJob()) + req.return_value.content = return_value + + request = service.CreateImportJobRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.ImportJob() + + client.create_import_job(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_crypto_key_rest_bad_request(request_type=service.UpdateCryptoKeyRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'crypto_key': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_crypto_key(request) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateCryptoKeyRequest, + dict, +]) +def test_update_crypto_key_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'crypto_key': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'}} + request_init["crypto_key"] = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4', 'primary': {'name': 'name_value', 'state': 5, 'protection_level': 1, 'algorithm': 1, 'attestation': {'format_': 3, 'content': b'content_blob', 'cert_chains': {'cavium_certs': ['cavium_certs_value1', 'cavium_certs_value2'], 'google_card_certs': ['google_card_certs_value1', 'google_card_certs_value2'], 'google_partition_certs': ['google_partition_certs_value1', 'google_partition_certs_value2']}}, 'create_time': {'seconds': 751, 'nanos': 543}, 'generate_time': {}, 'destroy_time': {}, 'destroy_event_time': {}, 'import_job': 'import_job_value', 'import_time': {}, 'import_failure_reason': 'import_failure_reason_value', 'generation_failure_reason': 'generation_failure_reason_value', 'external_destruction_failure_reason': 'external_destruction_failure_reason_value', 'external_protection_level_options': {'external_key_uri': 'external_key_uri_value', 'ekm_connection_key_path': 'ekm_connection_key_path_value'}, 'reimport_eligible': True}, 'purpose': 1, 'create_time': {}, 'next_rotation_time': {}, 'rotation_period': {'seconds': 751, 'nanos': 543}, 'version_template': {'protection_level': 1, 'algorithm': 1}, 'labels': {}, 'import_only': True, 'destroy_scheduled_duration': {}, 'crypto_key_backend': 'crypto_key_backend_value', 'key_access_justifications_policy': {'allowed_access_reasons': [1]}} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateCryptoKeyRequest.meta.fields["crypto_key"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["crypto_key"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["crypto_key"][field])): + del request_init["crypto_key"][field][i][subfield] + else: + del request_init["crypto_key"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_crypto_key(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_crypto_key_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_update_crypto_key") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_update_crypto_key") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCryptoKeyRequest.pb(service.UpdateCryptoKeyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CryptoKey.to_json(resources.CryptoKey()) + req.return_value.content = return_value + + request = service.UpdateCryptoKeyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKey() + + client.update_crypto_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_crypto_key_version_rest_bad_request(request_type=service.UpdateCryptoKeyVersionRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'crypto_key_version': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'}} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_crypto_key_version(request) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateCryptoKeyVersionRequest, + dict, +]) +def test_update_crypto_key_version_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'crypto_key_version': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'}} + request_init["crypto_key_version"] = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5', 'state': 5, 'protection_level': 1, 'algorithm': 1, 'attestation': {'format_': 3, 'content': b'content_blob', 'cert_chains': {'cavium_certs': ['cavium_certs_value1', 'cavium_certs_value2'], 'google_card_certs': ['google_card_certs_value1', 'google_card_certs_value2'], 'google_partition_certs': ['google_partition_certs_value1', 'google_partition_certs_value2']}}, 'create_time': {'seconds': 751, 'nanos': 543}, 'generate_time': {}, 'destroy_time': {}, 'destroy_event_time': {}, 'import_job': 'import_job_value', 'import_time': {}, 'import_failure_reason': 'import_failure_reason_value', 'generation_failure_reason': 'generation_failure_reason_value', 'external_destruction_failure_reason': 'external_destruction_failure_reason_value', 'external_protection_level_options': {'external_key_uri': 'external_key_uri_value', 'ekm_connection_key_path': 'ekm_connection_key_path_value'}, 'reimport_eligible': True} + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = service.UpdateCryptoKeyVersionRequest.meta.fields["crypto_key_version"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["crypto_key_version"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + {"field": field, "subfield": subfield, "is_repeated": is_repeated} + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["crypto_key_version"][field])): + del request_init["crypto_key_version"][field][i][subfield] + else: + del request_init["crypto_key_version"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_update_crypto_key_version") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_update_crypto_key_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCryptoKeyVersionRequest.pb(service.UpdateCryptoKeyVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) + req.return_value.content = return_value + + request = service.UpdateCryptoKeyVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.update_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_crypto_key_primary_version_rest_bad_request(request_type=service.UpdateCryptoKeyPrimaryVersionRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.update_crypto_key_primary_version(request) + + +@pytest.mark.parametrize("request_type", [ + service.UpdateCryptoKeyPrimaryVersionRequest, + dict, +]) +def test_update_crypto_key_primary_version_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKey( + name='name_value', + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend='crypto_key_backend_value', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKey.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.update_crypto_key_primary_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKey) + assert response.name == 'name_value' + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == 'crypto_key_backend_value' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_crypto_key_primary_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_update_crypto_key_primary_version") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_update_crypto_key_primary_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.UpdateCryptoKeyPrimaryVersionRequest.pb(service.UpdateCryptoKeyPrimaryVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CryptoKey.to_json(resources.CryptoKey()) + req.return_value.content = return_value + + request = service.UpdateCryptoKeyPrimaryVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKey() + + client.update_crypto_key_primary_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_destroy_crypto_key_version_rest_bad_request(request_type=service.DestroyCryptoKeyVersionRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.destroy_crypto_key_version(request) + + +@pytest.mark.parametrize("request_type", [ + service.DestroyCryptoKeyVersionRequest, + dict, +]) +def test_destroy_crypto_key_version_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(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.destroy_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_destroy_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_destroy_crypto_key_version") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_destroy_crypto_key_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DestroyCryptoKeyVersionRequest.pb(service.DestroyCryptoKeyVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) + req.return_value.content = return_value + + request = service.DestroyCryptoKeyVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.destroy_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_restore_crypto_key_version_rest_bad_request(request_type=service.RestoreCryptoKeyVersionRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.restore_crypto_key_version(request) + + +@pytest.mark.parametrize("request_type", [ + service.RestoreCryptoKeyVersionRequest, + dict, +]) +def test_restore_crypto_key_version_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = resources.CryptoKeyVersion( + name='name_value', + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job='import_job_value', + import_failure_reason='import_failure_reason_value', + generation_failure_reason='generation_failure_reason_value', + external_destruction_failure_reason='external_destruction_failure_reason_value', + reimport_eligible=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.pb(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.restore_crypto_key_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == 'name_value' + assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + assert response.import_job == 'import_job_value' + assert response.import_failure_reason == 'import_failure_reason_value' + assert response.generation_failure_reason == 'generation_failure_reason_value' + assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' + assert response.reimport_eligible is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_restore_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_restore_crypto_key_version") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_restore_crypto_key_version") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RestoreCryptoKeyVersionRequest.pb(service.RestoreCryptoKeyVersionRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) + req.return_value.content = return_value + + request = service.RestoreCryptoKeyVersionRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + + client.restore_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_encrypt_rest_bad_request(request_type=service.EncryptRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.encrypt(request) + + +@pytest.mark.parametrize("request_type", [ + service.EncryptRequest, + dict, +]) +def test_encrypt_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.EncryptResponse( + name='name_value', + ciphertext=b'ciphertext_blob', + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.EncryptResponse.pb(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.encrypt(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.EncryptResponse) + assert response.name == 'name_value' + assert response.ciphertext == b'ciphertext_blob' + assert response.verified_plaintext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_encrypt_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_encrypt") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_encrypt") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.EncryptRequest.pb(service.EncryptRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.EncryptResponse.to_json(service.EncryptResponse()) + req.return_value.content = return_value + + request = service.EncryptRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.EncryptResponse() + + client.encrypt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_decrypt_rest_bad_request(request_type=service.DecryptRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.decrypt(request) + + +@pytest.mark.parametrize("request_type", [ + service.DecryptRequest, + dict, +]) +def test_decrypt_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.DecryptResponse( + plaintext=b'plaintext_blob', + used_primary=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.DecryptResponse.pb(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.decrypt(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.DecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.used_primary is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_decrypt_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_decrypt") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_decrypt") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.DecryptRequest.pb(service.DecryptRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.DecryptResponse.to_json(service.DecryptResponse()) + req.return_value.content = return_value + + request = service.DecryptRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.DecryptResponse() + + client.decrypt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_raw_encrypt_rest_bad_request(request_type=service.RawEncryptRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.raw_encrypt(request) + + +@pytest.mark.parametrize("request_type", [ + service.RawEncryptRequest, + dict, +]) +def test_raw_encrypt_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.RawEncryptResponse( + ciphertext=b'ciphertext_blob', + initialization_vector=b'initialization_vector_blob', + tag_length=1053, + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, + name='name_value', + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.RawEncryptResponse.pb(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.raw_encrypt(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.RawEncryptResponse) + assert response.ciphertext == b'ciphertext_blob' + assert response.initialization_vector == b'initialization_vector_blob' + assert response.tag_length == 1053 + assert response.verified_plaintext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.verified_initialization_vector_crc32c is True + assert response.name == 'name_value' + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_raw_encrypt_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_raw_encrypt") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_raw_encrypt") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RawEncryptRequest.pb(service.RawEncryptRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.RawEncryptResponse.to_json(service.RawEncryptResponse()) + req.return_value.content = return_value + + request = service.RawEncryptRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.RawEncryptResponse() + + client.raw_encrypt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_raw_decrypt_rest_bad_request(request_type=service.RawDecryptRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.raw_decrypt(request) + + +@pytest.mark.parametrize("request_type", [ + service.RawDecryptRequest, + dict, +]) +def test_raw_decrypt_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.RawDecryptResponse( + plaintext=b'plaintext_blob', + protection_level=resources.ProtectionLevel.SOFTWARE, + verified_ciphertext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.RawDecryptResponse.pb(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.raw_decrypt(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.RawDecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.verified_ciphertext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.verified_initialization_vector_crc32c is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_raw_decrypt_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_raw_decrypt") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_raw_decrypt") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.RawDecryptRequest.pb(service.RawDecryptRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.RawDecryptResponse.to_json(service.RawDecryptResponse()) + req.return_value.content = return_value + + request = service.RawDecryptRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.RawDecryptResponse() + + client.raw_decrypt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_asymmetric_sign_rest_bad_request(request_type=service.AsymmetricSignRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.asymmetric_sign(request) + + +@pytest.mark.parametrize("request_type", [ + service.AsymmetricSignRequest, + dict, +]) +def test_asymmetric_sign_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricSignResponse( + signature=b'signature_blob', + verified_digest_crc32c=True, + name='name_value', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.AsymmetricSignResponse.pb(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.asymmetric_sign(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricSignResponse) + assert response.signature == b'signature_blob' + assert response.verified_digest_crc32c is True + assert response.name == 'name_value' + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_asymmetric_sign_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_asymmetric_sign") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_asymmetric_sign") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.AsymmetricSignRequest.pb(service.AsymmetricSignRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.AsymmetricSignResponse.to_json(service.AsymmetricSignResponse()) + req.return_value.content = return_value + + request = service.AsymmetricSignRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.AsymmetricSignResponse() + + client.asymmetric_sign(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_asymmetric_decrypt_rest_bad_request(request_type=service.AsymmetricDecryptRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.asymmetric_decrypt(request) + + +@pytest.mark.parametrize("request_type", [ + service.AsymmetricDecryptRequest, + dict, +]) +def test_asymmetric_decrypt_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.AsymmetricDecryptResponse( + plaintext=b'plaintext_blob', + verified_ciphertext_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.AsymmetricDecryptResponse.pb(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.asymmetric_decrypt(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricDecryptResponse) + assert response.plaintext == b'plaintext_blob' + assert response.verified_ciphertext_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_asymmetric_decrypt_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_asymmetric_decrypt") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_asymmetric_decrypt") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.AsymmetricDecryptRequest.pb(service.AsymmetricDecryptRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.AsymmetricDecryptResponse.to_json(service.AsymmetricDecryptResponse()) + req.return_value.content = return_value + + request = service.AsymmetricDecryptRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.AsymmetricDecryptResponse() + + client.asymmetric_decrypt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mac_sign_rest_bad_request(request_type=service.MacSignRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.mac_sign(request) + + +@pytest.mark.parametrize("request_type", [ + service.MacSignRequest, + dict, +]) +def test_mac_sign_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.MacSignResponse( + name='name_value', + mac=b'mac_blob', + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.MacSignResponse.pb(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.mac_sign(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacSignResponse) + assert response.name == 'name_value' + assert response.mac == b'mac_blob' + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mac_sign_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_mac_sign") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_mac_sign") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.MacSignRequest.pb(service.MacSignRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.MacSignResponse.to_json(service.MacSignResponse()) + req.return_value.content = return_value + + request = service.MacSignRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.MacSignResponse() + + client.mac_sign(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_mac_verify_rest_bad_request(request_type=service.MacVerifyRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.mac_verify(request) + + +@pytest.mark.parametrize("request_type", [ + service.MacVerifyRequest, + dict, +]) +def test_mac_verify_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.MacVerifyResponse( + name='name_value', + success=True, + verified_data_crc32c=True, + verified_mac_crc32c=True, + verified_success_integrity=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.MacVerifyResponse.pb(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.mac_verify(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.MacVerifyResponse) + assert response.name == 'name_value' + assert response.success is True + assert response.verified_data_crc32c is True + assert response.verified_mac_crc32c is True + assert response.verified_success_integrity is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_mac_verify_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_mac_verify") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_mac_verify") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.MacVerifyRequest.pb(service.MacVerifyRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.MacVerifyResponse.to_json(service.MacVerifyResponse()) + req.return_value.content = return_value + + request = service.MacVerifyRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.MacVerifyResponse() + + client.mac_verify(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_generate_random_bytes_rest_bad_request(request_type=service.GenerateRandomBytesRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {'location': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.generate_random_bytes(request) + + +@pytest.mark.parametrize("request_type", [ + service.GenerateRandomBytesRequest, + dict, +]) +def test_generate_random_bytes_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {'location': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), 'request') as req: + # Designate an appropriate value for the returned response. + return_value = service.GenerateRandomBytesResponse( + data=b'data_blob', + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.GenerateRandomBytesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + req.return_value = response_value + response = client.generate_random_bytes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateRandomBytesResponse) + assert response.data == b'data_blob' + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_generate_random_bytes_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with mock.patch.object(type(client.transport._session), "request") as req, \ + mock.patch.object(path_template, "transcode") as transcode, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_generate_random_bytes") as post, \ + mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_generate_random_bytes") as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GenerateRandomBytesRequest.pb(service.GenerateRandomBytesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.GenerateRandomBytesResponse.to_json(service.GenerateRandomBytesResponse()) + req.return_value.content = return_value + + request = service.GenerateRandomBytesRequest() + metadata =[ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.GenerateRandomBytesResponse() + + client.generate_random_bytes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_location(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.GetLocationRequest, + dict, +]) +def test_get_location_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_locations(request) + + +@pytest.mark.parametrize("request_type", [ + locations_pb2.ListLocationsRequest, + dict, +]) +def test_list_locations_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.GetIamPolicyRequest, + dict, +]) +def test_get_iam_policy_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.SetIamPolicyRequest, + dict, +]) +def test_set_iam_policy_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + +def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +@pytest.mark.parametrize("request_type", [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, +]) +def test_test_iam_permissions_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + +def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = '' + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_operation(request) + + +@pytest.mark.parametrize("request_type", [ + operations_pb2.GetOperationRequest, + dict, +]) +def test_get_operation_rest(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, 'request') as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode('UTF-8') + + req.return_value = response_value + + response = client.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_initialize_client_w_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_key_rings_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_key_rings), + '__call__') as call: + client.list_key_rings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListKeyRingsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_crypto_keys_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_keys), + '__call__') as call: + client.list_crypto_keys(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCryptoKeysRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_crypto_key_versions_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_crypto_key_versions), + '__call__') as call: + client.list_crypto_key_versions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListCryptoKeyVersionsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_import_jobs_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_import_jobs), + '__call__') as call: + client.list_import_jobs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListImportJobsRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_key_ring_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_key_ring), + '__call__') as call: + client.get_key_ring(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetKeyRingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_crypto_key_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key), + '__call__') as call: + client.get_crypto_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCryptoKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_crypto_key_version_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_crypto_key_version), + '__call__') as call: + client.get_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_public_key_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_public_key), + '__call__') as call: + client.get_public_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetPublicKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_import_job_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_import_job), + '__call__') as call: + client.get_import_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GetImportJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_key_ring_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_key_ring), + '__call__') as call: + client.create_key_ring(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateKeyRingRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_crypto_key_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key), + '__call__') as call: + client.create_crypto_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCryptoKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_crypto_key_version_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_crypto_key_version), + '__call__') as call: + client.create_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_import_crypto_key_version_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_crypto_key_version), + '__call__') as call: + client.import_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ImportCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_create_import_job_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_import_job), + '__call__') as call: + client.create_import_job(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.CreateImportJobRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_crypto_key_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key), + '__call__') as call: + client.update_crypto_key(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCryptoKeyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_crypto_key_version_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_version), + '__call__') as call: + client.update_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_update_crypto_key_primary_version_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_crypto_key_primary_version), + '__call__') as call: + client.update_crypto_key_primary_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.UpdateCryptoKeyPrimaryVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_destroy_crypto_key_version_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), + '__call__') as call: + client.destroy_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DestroyCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_restore_crypto_key_version_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.restore_crypto_key_version), + '__call__') as call: + client.restore_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RestoreCryptoKeyVersionRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_encrypt_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.encrypt), + '__call__') as call: + client.encrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EncryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_decrypt_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.decrypt), + '__call__') as call: + client.decrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DecryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_raw_encrypt_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.raw_encrypt), + '__call__') as call: + client.raw_encrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RawEncryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_raw_decrypt_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.raw_decrypt), + '__call__') as call: + client.raw_decrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RawDecryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_asymmetric_sign_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_sign), + '__call__') as call: + client.asymmetric_sign(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AsymmetricSignRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_asymmetric_decrypt_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.asymmetric_decrypt), + '__call__') as call: + client.asymmetric_decrypt(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.AsymmetricDecryptRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mac_sign_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mac_sign), + '__call__') as call: + client.mac_sign(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.MacSignRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_mac_verify_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.mac_verify), + '__call__') as call: + client.mac_verify(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.MacVerifyRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_generate_random_bytes_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), + '__call__') as call: + client.generate_random_bytes(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GenerateRandomBytesRequest() + + assert args[0] == request_msg + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.KeyManagementServiceGrpcTransport, + ) + +def test_key_management_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.KeyManagementServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json" + ) + + +def test_key_management_service_base_transport(): + # Instantiate the base transport. + with mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport.__init__') as Transport: + Transport.return_value = None + transport = transports.KeyManagementServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + 'list_key_rings', + 'list_crypto_keys', + 'list_crypto_key_versions', + 'list_import_jobs', + 'get_key_ring', + 'get_crypto_key', + 'get_crypto_key_version', + 'get_public_key', + 'get_import_job', + 'create_key_ring', + 'create_crypto_key', + 'create_crypto_key_version', + 'import_crypto_key_version', + 'create_import_job', + 'update_crypto_key', + 'update_crypto_key_version', + 'update_crypto_key_primary_version', + 'destroy_crypto_key_version', + 'restore_crypto_key_version', + 'encrypt', + 'decrypt', + 'raw_encrypt', + 'raw_decrypt', + 'asymmetric_sign', + 'asymmetric_decrypt', + 'mac_sign', + 'mac_verify', + 'generate_random_bytes', + 'set_iam_policy', + 'get_iam_policy', + 'test_iam_permissions', + 'get_location', + 'list_locations', + 'get_operation', + ) + 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_key_management_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KeyManagementServiceTransport( + 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', + 'https://www.googleapis.com/auth/cloudkms', +), + quota_project_id="octopus", + ) + + +def test_key_management_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages') as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.KeyManagementServiceTransport() + adc.assert_called_once() + + +def test_key_management_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + KeyManagementServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, + ], +) +def test_key_management_service_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloudkms',), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.KeyManagementServiceGrpcTransport, + transports.KeyManagementServiceGrpcAsyncIOTransport, + transports.KeyManagementServiceRestTransport, + ], +) +def test_key_management_service_transport_auth_gdch_credentials(transport_class): + host = 'https://language.com' + api_audience_tests = [None, 'https://language2.com'] + api_audience_expect = [host, 'https://language2.com'] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, 'default', autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with( + e + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.KeyManagementServiceGrpcTransport, grpc_helpers), + (transports.KeyManagementServiceGrpcAsyncIOTransport, grpc_helpers_async) + ], +) +def test_key_management_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class( + quota_project_id="octopus", + scopes=["1", "2"] + ) + + create_channel.assert_called_with( + "cloudkms.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/cloudkms', +), + scopes=["1", "2"], + default_host="cloudkms.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("transport_class", [transports.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) +def test_key_management_service_grpc_transport_client_cert_source_for_mtls( + transport_class +): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, + private_key=expected_key + ) + +def test_key_management_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: + transports.KeyManagementServiceRestTransport ( + 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_key_management_service_host_no_port(transport_name): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudkms.googleapis.com:443' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudkms.googleapis.com' + ) + +@pytest.mark.parametrize("transport_name", [ + "grpc", + "grpc_asyncio", + "rest", +]) +def test_key_management_service_host_with_port(transport_name): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com:8000'), + transport=transport_name, + ) + assert client.transport._host == ( + 'cloudkms.googleapis.com:8000' + if transport_name in ['grpc', 'grpc_asyncio'] + else 'https://cloudkms.googleapis.com:8000' + ) + +@pytest.mark.parametrize("transport_name", [ + "rest", +]) +def test_key_management_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = KeyManagementServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = KeyManagementServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_key_rings._session + session2 = client2.transport.list_key_rings._session + assert session1 != session2 + session1 = client1.transport.list_crypto_keys._session + session2 = client2.transport.list_crypto_keys._session + assert session1 != session2 + session1 = client1.transport.list_crypto_key_versions._session + session2 = client2.transport.list_crypto_key_versions._session + assert session1 != session2 + session1 = client1.transport.list_import_jobs._session + session2 = client2.transport.list_import_jobs._session + assert session1 != session2 + session1 = client1.transport.get_key_ring._session + session2 = client2.transport.get_key_ring._session + assert session1 != session2 + session1 = client1.transport.get_crypto_key._session + session2 = client2.transport.get_crypto_key._session + assert session1 != session2 + session1 = client1.transport.get_crypto_key_version._session + session2 = client2.transport.get_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.get_public_key._session + session2 = client2.transport.get_public_key._session + assert session1 != session2 + session1 = client1.transport.get_import_job._session + session2 = client2.transport.get_import_job._session + assert session1 != session2 + session1 = client1.transport.create_key_ring._session + session2 = client2.transport.create_key_ring._session + assert session1 != session2 + session1 = client1.transport.create_crypto_key._session + session2 = client2.transport.create_crypto_key._session + assert session1 != session2 + session1 = client1.transport.create_crypto_key_version._session + session2 = client2.transport.create_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.import_crypto_key_version._session + session2 = client2.transport.import_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.create_import_job._session + session2 = client2.transport.create_import_job._session + assert session1 != session2 + session1 = client1.transport.update_crypto_key._session + session2 = client2.transport.update_crypto_key._session + assert session1 != session2 + session1 = client1.transport.update_crypto_key_version._session + session2 = client2.transport.update_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.update_crypto_key_primary_version._session + session2 = client2.transport.update_crypto_key_primary_version._session + assert session1 != session2 + session1 = client1.transport.destroy_crypto_key_version._session + session2 = client2.transport.destroy_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.restore_crypto_key_version._session + session2 = client2.transport.restore_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.encrypt._session + session2 = client2.transport.encrypt._session + assert session1 != session2 + session1 = client1.transport.decrypt._session + session2 = client2.transport.decrypt._session + assert session1 != session2 + session1 = client1.transport.raw_encrypt._session + session2 = client2.transport.raw_encrypt._session + assert session1 != session2 + session1 = client1.transport.raw_decrypt._session + session2 = client2.transport.raw_decrypt._session + assert session1 != session2 + session1 = client1.transport.asymmetric_sign._session + session2 = client2.transport.asymmetric_sign._session + assert session1 != session2 + session1 = client1.transport.asymmetric_decrypt._session + session2 = client2.transport.asymmetric_decrypt._session + assert session1 != session2 + session1 = client1.transport.mac_sign._session + session2 = client2.transport.mac_sign._session + assert session1 != session2 + session1 = client1.transport.mac_verify._session + session2 = client2.transport.mac_verify._session + assert session1 != session2 + session1 = client1.transport.generate_random_bytes._session + session2 = client2.transport.generate_random_bytes._session + assert session1 != session2 +def test_key_management_service_grpc_transport_channel(): + channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.KeyManagementServiceGrpcTransport( + 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_key_management_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.KeyManagementServiceGrpcAsyncIOTransport( + 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.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) +def test_key_management_service_transport_channel_mtls_with_client_cert_source( + transport_class +): + with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, 'default') as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize("transport_class", [transports.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) +def test_key_management_service_transport_channel_mtls_with_adc( + transport_class +): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_crypto_key_path(): + project = "squid" + location = "clam" + key_ring = "whelk" + crypto_key = "octopus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) + actual = KeyManagementServiceClient.crypto_key_path(project, location, key_ring, crypto_key) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "key_ring": "cuttlefish", + "crypto_key": "mussel", + } + path = KeyManagementServiceClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_crypto_key_path(path) + assert expected == actual + +def test_crypto_key_version_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + actual = KeyManagementServiceClient.crypto_key_version_path(project, location, key_ring, crypto_key, crypto_key_version) + assert expected == actual + + +def test_parse_crypto_key_version_path(): + expected = { + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", + } + path = KeyManagementServiceClient.crypto_key_version_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_crypto_key_version_path(path) + assert expected == actual + +def test_import_job_path(): + project = "cuttlefish" + location = "mussel" + key_ring = "winkle" + import_job = "nautilus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format(project=project, location=location, key_ring=key_ring, import_job=import_job, ) + actual = KeyManagementServiceClient.import_job_path(project, location, key_ring, import_job) + assert expected == actual + + +def test_parse_import_job_path(): + expected = { + "project": "scallop", + "location": "abalone", + "key_ring": "squid", + "import_job": "clam", + } + path = KeyManagementServiceClient.import_job_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_import_job_path(path) + assert expected == actual + +def test_key_ring_path(): + project = "whelk" + location = "octopus" + key_ring = "oyster" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}".format(project=project, location=location, key_ring=key_ring, ) + actual = KeyManagementServiceClient.key_ring_path(project, location, key_ring) + assert expected == actual + + +def test_parse_key_ring_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "key_ring": "mussel", + } + path = KeyManagementServiceClient.key_ring_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_key_ring_path(path) + assert expected == actual + +def test_public_key_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) + actual = KeyManagementServiceClient.public_key_path(project, location, key_ring, crypto_key, crypto_key_version) + assert expected == actual + + +def test_parse_public_key_path(): + expected = { + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", + } + path = KeyManagementServiceClient.public_key_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_public_key_path(path) + assert expected == actual + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) + actual = KeyManagementServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = KeyManagementServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_billing_account_path(path) + assert expected == actual + +def test_common_folder_path(): + folder = "winkle" + expected = "folders/{folder}".format(folder=folder, ) + actual = KeyManagementServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = KeyManagementServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_folder_path(path) + assert expected == actual + +def test_common_organization_path(): + organization = "scallop" + expected = "organizations/{organization}".format(organization=organization, ) + actual = KeyManagementServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = KeyManagementServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.parse_common_organization_path(path) + assert expected == actual + +def test_common_project_path(): + project = "squid" + expected = "projects/{project}".format(project=project, ) + actual = KeyManagementServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = KeyManagementServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.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 = KeyManagementServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = KeyManagementServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = KeyManagementServiceClient.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.KeyManagementServiceTransport, '_prep_wrapped_messages') as prep: + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.KeyManagementServiceTransport, '_prep_wrapped_messages') as prep: + transport_class = KeyManagementServiceClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_get_operation(transport: str = "grpc"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + +def test_get_operation_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value 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 = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_get_operation_from_dict(): + client = KeyManagementServiceClient( + 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 = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_list_locations(transport: str = "grpc"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc_asyncio"): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.ListLocationsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + +def test_list_locations_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() + + client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.ListLocationsRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations",) in kw["metadata"] + +def test_list_locations_from_dict(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_get_location(transport: str = "grpc"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = locations_pb2.GetLocationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + +def test_get_location_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials()) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() + + client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials() + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = locations_pb2.GetLocationRequest() + request.name = "locations/abc" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] + +def test_get_location_from_dict(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + + response = client.get_location( + request={ + "name": "locations/abc", + } + ) + call.assert_called() +@pytest.mark.asyncio +async def test_get_location_from_dict_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_set_iam_policy(transport: str = "grpc"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + response = client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" +@pytest.mark.asyncio +async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.SetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + response = await client.set_iam_policy(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + +def test_set_iam_policy_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + +def test_set_iam_policy_from_dict(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_set_iam_policy_from_dict_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy_pb2.Policy(version=774), + } + ) + call.assert_called() + + +def test_get_iam_policy(transport: str = "grpc"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.GetIamPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + call.return_value = policy_pb2.Policy() + + client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_iam_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = policy_pb2.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_get_iam_policy_from_dict_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_pb2.Policy() + ) + + response = await client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_test_iam_permissions(transport: str = "grpc"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = iam_policy_pb2.TestIamPermissionsRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + +@pytest.mark.asyncio +async def test_test_iam_permissions_from_dict_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.test_iam_permissions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + response = await client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_transport_close_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +@pytest.mark.asyncio +async def test_transport_close_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio" + ) + with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_transport_close_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest" + ) + with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + 'rest', + 'grpc', + ] + for transport in transports: + client = KeyManagementServiceClient( + 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", [ + (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport), + (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport), +]) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) From 5e07803b95458d055343ac3488642c7425b9a5e3 Mon Sep 17 00:00:00 2001 From: Owl Bot Date: Tue, 26 Nov 2024 17:17:56 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=A6=89=20Updates=20from=20OwlBot=20po?= =?UTF-8?q?st-processor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --- .../google-cloud-kms/v1/.coveragerc | 13 - owl-bot-staging/google-cloud-kms/v1/.flake8 | 33 - .../google-cloud-kms/v1/MANIFEST.in | 2 - .../google-cloud-kms/v1/README.rst | 49 - .../v1/docs/_static/custom.css | 3 - .../google-cloud-kms/v1/docs/conf.py | 376 - .../google-cloud-kms/v1/docs/index.rst | 7 - .../v1/docs/kms_v1/autokey.rst | 10 - .../v1/docs/kms_v1/autokey_admin.rst | 6 - .../v1/docs/kms_v1/ekm_service.rst | 10 - .../v1/docs/kms_v1/key_management_service.rst | 10 - .../v1/docs/kms_v1/services_.rst | 9 - .../v1/docs/kms_v1/types_.rst | 6 - .../v1/google/cloud/kms/__init__.py | 193 - .../v1/google/cloud/kms/gapic_version.py | 16 - .../v1/google/cloud/kms/py.typed | 2 - .../v1/google/cloud/kms_v1/__init__.py | 194 - .../google/cloud/kms_v1/gapic_metadata.json | 700 - .../v1/google/cloud/kms_v1/gapic_version.py | 16 - .../v1/google/cloud/kms_v1/py.typed | 2 - .../google/cloud/kms_v1/services/__init__.py | 15 - .../cloud/kms_v1/services/autokey/__init__.py | 22 - .../kms_v1/services/autokey/async_client.py | 1074 - .../cloud/kms_v1/services/autokey/client.py | 1423 - .../cloud/kms_v1/services/autokey/pagers.py | 162 - .../services/autokey/transports/README.rst | 9 - .../services/autokey/transports/__init__.py | 38 - .../services/autokey/transports/base.py | 298 - .../services/autokey/transports/grpc.py | 502 - .../autokey/transports/grpc_asyncio.py | 584 - .../services/autokey/transports/rest.py | 1119 - .../services/autokey/transports/rest_base.py | 434 - .../kms_v1/services/autokey_admin/__init__.py | 22 - .../services/autokey_admin/async_client.py | 1018 - .../kms_v1/services/autokey_admin/client.py | 1358 - .../autokey_admin/transports/README.rst | 9 - .../autokey_admin/transports/__init__.py | 38 - .../services/autokey_admin/transports/base.py | 302 - .../services/autokey_admin/transports/grpc.py | 477 - .../autokey_admin/transports/grpc_asyncio.py | 569 - .../services/autokey_admin/transports/rest.py | 1077 - .../autokey_admin/transports/rest_base.py | 434 - .../kms_v1/services/ekm_service/__init__.py | 22 - .../services/ekm_service/async_client.py | 1526 - .../kms_v1/services/ekm_service/client.py | 1880 -- .../kms_v1/services/ekm_service/pagers.py | 162 - .../ekm_service/transports/README.rst | 9 - .../ekm_service/transports/__init__.py | 38 - .../services/ekm_service/transports/base.py | 368 - .../services/ekm_service/transports/grpc.py | 579 - .../ekm_service/transports/grpc_asyncio.py | 701 - .../services/ekm_service/transports/rest.py | 1553 -- .../ekm_service/transports/rest_base.py | 602 - .../key_management_service/__init__.py | 22 - .../key_management_service/async_client.py | 4163 --- .../services/key_management_service/client.py | 4517 --- .../services/key_management_service/pagers.py | 568 - .../transports/README.rst | 9 - .../transports/__init__.py | 38 - .../key_management_service/transports/base.py | 863 - .../key_management_service/transports/grpc.py | 1250 - .../transports/grpc_asyncio.py | 1677 -- .../key_management_service/transports/rest.py | 4008 --- .../transports/rest_base.py | 1532 -- .../v1/google/cloud/kms_v1/types/__init__.py | 182 - .../v1/google/cloud/kms_v1/types/autokey.py | 214 - .../cloud/kms_v1/types/autokey_admin.py | 178 - .../google/cloud/kms_v1/types/ekm_service.py | 554 - .../v1/google/cloud/kms_v1/types/resources.py | 1383 - .../v1/google/cloud/kms_v1/types/service.py | 2528 -- owl-bot-staging/google-cloud-kms/v1/mypy.ini | 3 - .../google-cloud-kms/v1/noxfile.py | 280 - ..._autokey_admin_get_autokey_config_async.py | 52 - ...d_autokey_admin_get_autokey_config_sync.py | 52 - ...min_show_effective_autokey_config_async.py | 52 - ...dmin_show_effective_autokey_config_sync.py | 52 - ...tokey_admin_update_autokey_config_async.py | 51 - ...utokey_admin_update_autokey_config_sync.py | 51 - ...nerated_autokey_create_key_handle_async.py | 60 - ...enerated_autokey_create_key_handle_sync.py | 60 - ..._generated_autokey_get_key_handle_async.py | 52 - ...1_generated_autokey_get_key_handle_sync.py | 52 - ...enerated_autokey_list_key_handles_async.py | 53 - ...generated_autokey_list_key_handles_sync.py | 53 - ...ekm_service_create_ekm_connection_async.py | 53 - ..._ekm_service_create_ekm_connection_sync.py | 53 - ...erated_ekm_service_get_ekm_config_async.py | 52 - ...nerated_ekm_service_get_ekm_config_sync.py | 52 - ...ed_ekm_service_get_ekm_connection_async.py | 52 - ...ted_ekm_service_get_ekm_connection_sync.py | 52 - ..._ekm_service_list_ekm_connections_async.py | 53 - ...d_ekm_service_list_ekm_connections_sync.py | 53 - ...ted_ekm_service_update_ekm_config_async.py | 51 - ...ated_ekm_service_update_ekm_config_sync.py | 51 - ...ekm_service_update_ekm_connection_async.py | 51 - ..._ekm_service_update_ekm_connection_sync.py | 51 - ...d_ekm_service_verify_connectivity_async.py | 52 - ...ed_ekm_service_verify_connectivity_sync.py | 52 - ...gement_service_asymmetric_decrypt_async.py | 53 - ...agement_service_asymmetric_decrypt_sync.py | 53 - ...anagement_service_asymmetric_sign_async.py | 52 - ...management_service_asymmetric_sign_sync.py | 52 - ...agement_service_create_crypto_key_async.py | 53 - ...nagement_service_create_crypto_key_sync.py | 53 - ...service_create_crypto_key_version_async.py | 52 - ..._service_create_crypto_key_version_sync.py | 52 - ...agement_service_create_import_job_async.py | 58 - ...nagement_service_create_import_job_sync.py | 58 - ...anagement_service_create_key_ring_async.py | 53 - ...management_service_create_key_ring_sync.py | 53 - ...ed_key_management_service_decrypt_async.py | 53 - ...ted_key_management_service_decrypt_sync.py | 53 - ...ervice_destroy_crypto_key_version_async.py | 52 - ...service_destroy_crypto_key_version_sync.py | 52 - ...ed_key_management_service_encrypt_async.py | 53 - ...ted_key_management_service_encrypt_sync.py | 53 - ...ent_service_generate_random_bytes_async.py | 51 - ...ment_service_generate_random_bytes_sync.py | 51 - ...management_service_get_crypto_key_async.py | 52 - ..._management_service_get_crypto_key_sync.py | 52 - ...nt_service_get_crypto_key_version_async.py | 52 - ...ent_service_get_crypto_key_version_sync.py | 52 - ...management_service_get_import_job_async.py | 52 - ..._management_service_get_import_job_sync.py | 52 - ...y_management_service_get_key_ring_async.py | 52 - ...ey_management_service_get_key_ring_sync.py | 52 - ...management_service_get_public_key_async.py | 52 - ..._management_service_get_public_key_sync.py | 52 - ...service_import_crypto_key_version_async.py | 55 - ..._service_import_crypto_key_version_sync.py | 55 - ..._service_list_crypto_key_versions_async.py | 53 - ...t_service_list_crypto_key_versions_sync.py | 53 - ...nagement_service_list_crypto_keys_async.py | 53 - ...anagement_service_list_crypto_keys_sync.py | 53 - ...nagement_service_list_import_jobs_async.py | 53 - ...anagement_service_list_import_jobs_sync.py | 53 - ...management_service_list_key_rings_async.py | 53 - ..._management_service_list_key_rings_sync.py | 53 - ...d_key_management_service_mac_sign_async.py | 53 - ...ed_key_management_service_mac_sign_sync.py | 53 - ...key_management_service_mac_verify_async.py | 54 - ..._key_management_service_mac_verify_sync.py | 54 - ...ey_management_service_raw_decrypt_async.py | 54 - ...key_management_service_raw_decrypt_sync.py | 54 - ...ey_management_service_raw_encrypt_async.py | 53 - ...key_management_service_raw_encrypt_sync.py | 53 - ...ervice_restore_crypto_key_version_async.py | 52 - ...service_restore_crypto_key_version_sync.py | 52 - ...agement_service_update_crypto_key_async.py | 51 - ...update_crypto_key_primary_version_async.py | 53 - ..._update_crypto_key_primary_version_sync.py | 53 - ...nagement_service_update_crypto_key_sync.py | 51 - ...service_update_crypto_key_version_async.py | 51 - ..._service_update_crypto_key_version_sync.py | 51 - .../snippet_metadata_google.cloud.kms.v1.json | 6800 ----- .../v1/scripts/fixup_kms_v1_keywords.py | 219 - owl-bot-staging/google-cloud-kms/v1/setup.py | 99 - .../v1/testing/constraints-3.10.txt | 7 - .../v1/testing/constraints-3.11.txt | 7 - .../v1/testing/constraints-3.12.txt | 7 - .../v1/testing/constraints-3.13.txt | 7 - .../v1/testing/constraints-3.7.txt | 11 - .../v1/testing/constraints-3.8.txt | 7 - .../v1/testing/constraints-3.9.txt | 7 - .../google-cloud-kms/v1/tests/__init__.py | 16 - .../v1/tests/unit/__init__.py | 16 - .../v1/tests/unit/gapic/__init__.py | 16 - .../v1/tests/unit/gapic/kms_v1/__init__.py | 16 - .../tests/unit/gapic/kms_v1/test_autokey.py | 5012 ---- .../unit/gapic/kms_v1/test_autokey_admin.py | 4652 ---- .../unit/gapic/kms_v1/test_ekm_service.py | 7787 ------ .../kms_v1/test_key_management_service.py | 22906 ---------------- .../google/cloud/kms/gapic_version.py | 2 +- .../google/cloud/kms_v1/gapic_version.py | 2 +- .../google/cloud/kms_v1/types/resources.py | 2 + .../snippet_metadata_google.cloud.kms.v1.json | 2 +- 176 files changed, 5 insertions(+), 95969 deletions(-) delete mode 100644 owl-bot-staging/google-cloud-kms/v1/.coveragerc delete mode 100644 owl-bot-staging/google-cloud-kms/v1/.flake8 delete mode 100644 owl-bot-staging/google-cloud-kms/v1/MANIFEST.in delete mode 100644 owl-bot-staging/google-cloud-kms/v1/README.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/_static/custom.css delete mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/conf.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/index.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey_admin.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/ekm_service.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/key_management_service.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/services_.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/types_.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/py.typed delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_metadata.json delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_version.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/py.typed delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/async_client.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/client.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/pagers.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/async_client.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/client.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/client.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/async_client.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/client.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/pagers.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/README.rst delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey_admin.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/ekm_service.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/resources.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/service.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/mypy.ini delete mode 100644 owl-bot-staging/google-cloud-kms/v1/noxfile.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json delete mode 100644 owl-bot-staging/google-cloud-kms/v1/scripts/fixup_kms_v1_keywords.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/setup.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.10.txt delete mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.11.txt delete mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.12.txt delete mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.13.txt delete mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.7.txt delete mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.8.txt delete mode 100644 owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.9.txt delete mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/__init__.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey_admin.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_ekm_service.py delete mode 100644 owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_key_management_service.py diff --git a/owl-bot-staging/google-cloud-kms/v1/.coveragerc b/owl-bot-staging/google-cloud-kms/v1/.coveragerc deleted file mode 100644 index ada4b5e633e6..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/.coveragerc +++ /dev/null @@ -1,13 +0,0 @@ -[run] -branch = True - -[report] -show_missing = True -omit = - google/cloud/kms/__init__.py - google/cloud/kms/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-kms/v1/.flake8 b/owl-bot-staging/google-cloud-kms/v1/.flake8 deleted file mode 100644 index 29227d4cf419..000000000000 --- a/owl-bot-staging/google-cloud-kms/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-kms/v1/MANIFEST.in b/owl-bot-staging/google-cloud-kms/v1/MANIFEST.in deleted file mode 100644 index 97846726fb83..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -recursive-include google/cloud/kms *.py -recursive-include google/cloud/kms_v1 *.py diff --git a/owl-bot-staging/google-cloud-kms/v1/README.rst b/owl-bot-staging/google-cloud-kms/v1/README.rst deleted file mode 100644 index 9574e81c7eb6..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/README.rst +++ /dev/null @@ -1,49 +0,0 @@ -Python Client for Google Cloud Kms 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 Kms 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-kms/v1/docs/_static/custom.css b/owl-bot-staging/google-cloud-kms/v1/docs/_static/custom.css deleted file mode 100644 index 06423be0b592..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/docs/_static/custom.css +++ /dev/null @@ -1,3 +0,0 @@ -dl.field-list > dt { - min-width: 100px -} diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/conf.py b/owl-bot-staging/google-cloud-kms/v1/docs/conf.py deleted file mode 100644 index 7c9dfa8fbd1b..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/docs/conf.py +++ /dev/null @@ -1,376 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# google-cloud-kms 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-kms" -copyright = u"2023, Google, LLC" -author = u"Google APIs" # TODO: autogenerate this bit - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The full version, including alpha/beta/rc tags. -release = __version__ -# The short X.Y version. -version = ".".join(release.split(".")[0:2]) - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'en' - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -exclude_patterns = ["_build"] - -# The reST default role (used for this markup: `text`) to use for all -# documents. -# default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True - - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = "alabaster" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -html_theme_options = { - "description": "Google Cloud Client Libraries for Python", - "github_user": "googleapis", - "github_repo": "google-cloud-python", - "github_banner": True, - "font_family": "'Roboto', Georgia, sans", - "head_font_family": "'Roboto', Georgia, serif", - "code_font_family": "'Roboto Mono', 'Consolas', monospace", -} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None - -# Language to be used for generating the HTML full-text search index. -# Sphinx supports the following languages: -# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' -# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' -# html_search_language = 'en' - -# A dictionary with options for the search language support, empty by default. -# Now only 'ja' uses this config value -# html_search_options = {'type': 'default'} - -# The name of a javascript file (relative to the configuration directory) that -# implements a search results scorer. If empty, the default will be used. -# html_search_scorer = 'scorer.js' - -# Output file base name for HTML help builder. -htmlhelp_basename = "google-cloud-kms-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-kms.tex", - u"google-cloud-kms 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-kms", - u"Google Cloud Kms 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-kms", - u"google-cloud-kms Documentation", - author, - "google-cloud-kms", - "GAPIC library for Google Cloud Kms 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-kms/v1/docs/index.rst b/owl-bot-staging/google-cloud-kms/v1/docs/index.rst deleted file mode 100644 index 8d79aeb30d1d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/docs/index.rst +++ /dev/null @@ -1,7 +0,0 @@ -API Reference -------------- -.. toctree:: - :maxdepth: 2 - - kms_v1/services_ - kms_v1/types_ diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey.rst deleted file mode 100644 index 266646a17c28..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey.rst +++ /dev/null @@ -1,10 +0,0 @@ -Autokey -------------------------- - -.. automodule:: google.cloud.kms_v1.services.autokey - :members: - :inherited-members: - -.. automodule:: google.cloud.kms_v1.services.autokey.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey_admin.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey_admin.rst deleted file mode 100644 index ae47377233b2..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/autokey_admin.rst +++ /dev/null @@ -1,6 +0,0 @@ -AutokeyAdmin ------------------------------- - -.. automodule:: google.cloud.kms_v1.services.autokey_admin - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/ekm_service.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/ekm_service.rst deleted file mode 100644 index 82f6e2a430b8..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/ekm_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -EkmService ----------------------------- - -.. automodule:: google.cloud.kms_v1.services.ekm_service - :members: - :inherited-members: - -.. automodule:: google.cloud.kms_v1.services.ekm_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/key_management_service.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/key_management_service.rst deleted file mode 100644 index b34ce0281bb2..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/key_management_service.rst +++ /dev/null @@ -1,10 +0,0 @@ -KeyManagementService --------------------------------------- - -.. automodule:: google.cloud.kms_v1.services.key_management_service - :members: - :inherited-members: - -.. automodule:: google.cloud.kms_v1.services.key_management_service.pagers - :members: - :inherited-members: diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/services_.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/services_.rst deleted file mode 100644 index 18fe1076d51a..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/services_.rst +++ /dev/null @@ -1,9 +0,0 @@ -Services for Google Cloud Kms v1 API -==================================== -.. toctree:: - :maxdepth: 2 - - autokey - autokey_admin - ekm_service - key_management_service diff --git a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/types_.rst b/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/types_.rst deleted file mode 100644 index c78ef915f3a0..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/docs/kms_v1/types_.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Kms v1 API -================================= - -.. automodule:: google.cloud.kms_v1.types - :members: - :show-inheritance: diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/__init__.py deleted file mode 100644 index 745e815f595c..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/__init__.py +++ /dev/null @@ -1,193 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.kms import gapic_version as package_version - -__version__ = package_version.__version__ - - -from google.cloud.kms_v1.services.autokey.client import AutokeyClient -from google.cloud.kms_v1.services.autokey.async_client import AutokeyAsyncClient -from google.cloud.kms_v1.services.autokey_admin.client import AutokeyAdminClient -from google.cloud.kms_v1.services.autokey_admin.async_client import AutokeyAdminAsyncClient -from google.cloud.kms_v1.services.ekm_service.client import EkmServiceClient -from google.cloud.kms_v1.services.ekm_service.async_client import EkmServiceAsyncClient -from google.cloud.kms_v1.services.key_management_service.client import KeyManagementServiceClient -from google.cloud.kms_v1.services.key_management_service.async_client import KeyManagementServiceAsyncClient - -from google.cloud.kms_v1.types.autokey import CreateKeyHandleMetadata -from google.cloud.kms_v1.types.autokey import CreateKeyHandleRequest -from google.cloud.kms_v1.types.autokey import GetKeyHandleRequest -from google.cloud.kms_v1.types.autokey import KeyHandle -from google.cloud.kms_v1.types.autokey import ListKeyHandlesRequest -from google.cloud.kms_v1.types.autokey import ListKeyHandlesResponse -from google.cloud.kms_v1.types.autokey_admin import AutokeyConfig -from google.cloud.kms_v1.types.autokey_admin import GetAutokeyConfigRequest -from google.cloud.kms_v1.types.autokey_admin import ShowEffectiveAutokeyConfigRequest -from google.cloud.kms_v1.types.autokey_admin import ShowEffectiveAutokeyConfigResponse -from google.cloud.kms_v1.types.autokey_admin import UpdateAutokeyConfigRequest -from google.cloud.kms_v1.types.ekm_service import Certificate -from google.cloud.kms_v1.types.ekm_service import CreateEkmConnectionRequest -from google.cloud.kms_v1.types.ekm_service import EkmConfig -from google.cloud.kms_v1.types.ekm_service import EkmConnection -from google.cloud.kms_v1.types.ekm_service import GetEkmConfigRequest -from google.cloud.kms_v1.types.ekm_service import GetEkmConnectionRequest -from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsRequest -from google.cloud.kms_v1.types.ekm_service import ListEkmConnectionsResponse -from google.cloud.kms_v1.types.ekm_service import UpdateEkmConfigRequest -from google.cloud.kms_v1.types.ekm_service import UpdateEkmConnectionRequest -from google.cloud.kms_v1.types.ekm_service import VerifyConnectivityRequest -from google.cloud.kms_v1.types.ekm_service import VerifyConnectivityResponse -from google.cloud.kms_v1.types.resources import CryptoKey -from google.cloud.kms_v1.types.resources import CryptoKeyVersion -from google.cloud.kms_v1.types.resources import CryptoKeyVersionTemplate -from google.cloud.kms_v1.types.resources import ExternalProtectionLevelOptions -from google.cloud.kms_v1.types.resources import ImportJob -from google.cloud.kms_v1.types.resources import KeyAccessJustificationsPolicy -from google.cloud.kms_v1.types.resources import KeyOperationAttestation -from google.cloud.kms_v1.types.resources import KeyRing -from google.cloud.kms_v1.types.resources import PublicKey -from google.cloud.kms_v1.types.resources import AccessReason -from google.cloud.kms_v1.types.resources import ProtectionLevel -from google.cloud.kms_v1.types.service import AsymmetricDecryptRequest -from google.cloud.kms_v1.types.service import AsymmetricDecryptResponse -from google.cloud.kms_v1.types.service import AsymmetricSignRequest -from google.cloud.kms_v1.types.service import AsymmetricSignResponse -from google.cloud.kms_v1.types.service import CreateCryptoKeyRequest -from google.cloud.kms_v1.types.service import CreateCryptoKeyVersionRequest -from google.cloud.kms_v1.types.service import CreateImportJobRequest -from google.cloud.kms_v1.types.service import CreateKeyRingRequest -from google.cloud.kms_v1.types.service import DecryptRequest -from google.cloud.kms_v1.types.service import DecryptResponse -from google.cloud.kms_v1.types.service import DestroyCryptoKeyVersionRequest -from google.cloud.kms_v1.types.service import Digest -from google.cloud.kms_v1.types.service import EncryptRequest -from google.cloud.kms_v1.types.service import EncryptResponse -from google.cloud.kms_v1.types.service import GenerateRandomBytesRequest -from google.cloud.kms_v1.types.service import GenerateRandomBytesResponse -from google.cloud.kms_v1.types.service import GetCryptoKeyRequest -from google.cloud.kms_v1.types.service import GetCryptoKeyVersionRequest -from google.cloud.kms_v1.types.service import GetImportJobRequest -from google.cloud.kms_v1.types.service import GetKeyRingRequest -from google.cloud.kms_v1.types.service import GetPublicKeyRequest -from google.cloud.kms_v1.types.service import ImportCryptoKeyVersionRequest -from google.cloud.kms_v1.types.service import ListCryptoKeysRequest -from google.cloud.kms_v1.types.service import ListCryptoKeysResponse -from google.cloud.kms_v1.types.service import ListCryptoKeyVersionsRequest -from google.cloud.kms_v1.types.service import ListCryptoKeyVersionsResponse -from google.cloud.kms_v1.types.service import ListImportJobsRequest -from google.cloud.kms_v1.types.service import ListImportJobsResponse -from google.cloud.kms_v1.types.service import ListKeyRingsRequest -from google.cloud.kms_v1.types.service import ListKeyRingsResponse -from google.cloud.kms_v1.types.service import LocationMetadata -from google.cloud.kms_v1.types.service import MacSignRequest -from google.cloud.kms_v1.types.service import MacSignResponse -from google.cloud.kms_v1.types.service import MacVerifyRequest -from google.cloud.kms_v1.types.service import MacVerifyResponse -from google.cloud.kms_v1.types.service import RawDecryptRequest -from google.cloud.kms_v1.types.service import RawDecryptResponse -from google.cloud.kms_v1.types.service import RawEncryptRequest -from google.cloud.kms_v1.types.service import RawEncryptResponse -from google.cloud.kms_v1.types.service import RestoreCryptoKeyVersionRequest -from google.cloud.kms_v1.types.service import UpdateCryptoKeyPrimaryVersionRequest -from google.cloud.kms_v1.types.service import UpdateCryptoKeyRequest -from google.cloud.kms_v1.types.service import UpdateCryptoKeyVersionRequest - -__all__ = ('AutokeyClient', - 'AutokeyAsyncClient', - 'AutokeyAdminClient', - 'AutokeyAdminAsyncClient', - 'EkmServiceClient', - 'EkmServiceAsyncClient', - 'KeyManagementServiceClient', - 'KeyManagementServiceAsyncClient', - 'CreateKeyHandleMetadata', - 'CreateKeyHandleRequest', - 'GetKeyHandleRequest', - 'KeyHandle', - 'ListKeyHandlesRequest', - 'ListKeyHandlesResponse', - 'AutokeyConfig', - 'GetAutokeyConfigRequest', - 'ShowEffectiveAutokeyConfigRequest', - 'ShowEffectiveAutokeyConfigResponse', - 'UpdateAutokeyConfigRequest', - 'Certificate', - 'CreateEkmConnectionRequest', - 'EkmConfig', - 'EkmConnection', - 'GetEkmConfigRequest', - 'GetEkmConnectionRequest', - 'ListEkmConnectionsRequest', - 'ListEkmConnectionsResponse', - 'UpdateEkmConfigRequest', - 'UpdateEkmConnectionRequest', - 'VerifyConnectivityRequest', - 'VerifyConnectivityResponse', - 'CryptoKey', - 'CryptoKeyVersion', - 'CryptoKeyVersionTemplate', - 'ExternalProtectionLevelOptions', - 'ImportJob', - 'KeyAccessJustificationsPolicy', - 'KeyOperationAttestation', - 'KeyRing', - 'PublicKey', - 'AccessReason', - 'ProtectionLevel', - 'AsymmetricDecryptRequest', - 'AsymmetricDecryptResponse', - 'AsymmetricSignRequest', - 'AsymmetricSignResponse', - 'CreateCryptoKeyRequest', - 'CreateCryptoKeyVersionRequest', - 'CreateImportJobRequest', - 'CreateKeyRingRequest', - 'DecryptRequest', - 'DecryptResponse', - 'DestroyCryptoKeyVersionRequest', - 'Digest', - 'EncryptRequest', - 'EncryptResponse', - 'GenerateRandomBytesRequest', - 'GenerateRandomBytesResponse', - 'GetCryptoKeyRequest', - 'GetCryptoKeyVersionRequest', - 'GetImportJobRequest', - 'GetKeyRingRequest', - 'GetPublicKeyRequest', - 'ImportCryptoKeyVersionRequest', - 'ListCryptoKeysRequest', - 'ListCryptoKeysResponse', - 'ListCryptoKeyVersionsRequest', - 'ListCryptoKeyVersionsResponse', - 'ListImportJobsRequest', - 'ListImportJobsResponse', - 'ListKeyRingsRequest', - 'ListKeyRingsResponse', - 'LocationMetadata', - 'MacSignRequest', - 'MacSignResponse', - 'MacVerifyRequest', - 'MacVerifyResponse', - 'RawDecryptRequest', - 'RawDecryptResponse', - 'RawEncryptRequest', - 'RawEncryptResponse', - 'RestoreCryptoKeyVersionRequest', - 'UpdateCryptoKeyPrimaryVersionRequest', - 'UpdateCryptoKeyRequest', - 'UpdateCryptoKeyVersionRequest', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/gapic_version.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/py.typed b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/py.typed deleted file mode 100644 index 3720b5f23ae9..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-kms package uses inline types. diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/__init__.py deleted file mode 100644 index 2ad2f667cccc..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/__init__.py +++ /dev/null @@ -1,194 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.kms_v1 import gapic_version as package_version - -__version__ = package_version.__version__ - - -from .services.autokey import AutokeyClient -from .services.autokey import AutokeyAsyncClient -from .services.autokey_admin import AutokeyAdminClient -from .services.autokey_admin import AutokeyAdminAsyncClient -from .services.ekm_service import EkmServiceClient -from .services.ekm_service import EkmServiceAsyncClient -from .services.key_management_service import KeyManagementServiceClient -from .services.key_management_service import KeyManagementServiceAsyncClient - -from .types.autokey import CreateKeyHandleMetadata -from .types.autokey import CreateKeyHandleRequest -from .types.autokey import GetKeyHandleRequest -from .types.autokey import KeyHandle -from .types.autokey import ListKeyHandlesRequest -from .types.autokey import ListKeyHandlesResponse -from .types.autokey_admin import AutokeyConfig -from .types.autokey_admin import GetAutokeyConfigRequest -from .types.autokey_admin import ShowEffectiveAutokeyConfigRequest -from .types.autokey_admin import ShowEffectiveAutokeyConfigResponse -from .types.autokey_admin import UpdateAutokeyConfigRequest -from .types.ekm_service import Certificate -from .types.ekm_service import CreateEkmConnectionRequest -from .types.ekm_service import EkmConfig -from .types.ekm_service import EkmConnection -from .types.ekm_service import GetEkmConfigRequest -from .types.ekm_service import GetEkmConnectionRequest -from .types.ekm_service import ListEkmConnectionsRequest -from .types.ekm_service import ListEkmConnectionsResponse -from .types.ekm_service import UpdateEkmConfigRequest -from .types.ekm_service import UpdateEkmConnectionRequest -from .types.ekm_service import VerifyConnectivityRequest -from .types.ekm_service import VerifyConnectivityResponse -from .types.resources import CryptoKey -from .types.resources import CryptoKeyVersion -from .types.resources import CryptoKeyVersionTemplate -from .types.resources import ExternalProtectionLevelOptions -from .types.resources import ImportJob -from .types.resources import KeyAccessJustificationsPolicy -from .types.resources import KeyOperationAttestation -from .types.resources import KeyRing -from .types.resources import PublicKey -from .types.resources import AccessReason -from .types.resources import ProtectionLevel -from .types.service import AsymmetricDecryptRequest -from .types.service import AsymmetricDecryptResponse -from .types.service import AsymmetricSignRequest -from .types.service import AsymmetricSignResponse -from .types.service import CreateCryptoKeyRequest -from .types.service import CreateCryptoKeyVersionRequest -from .types.service import CreateImportJobRequest -from .types.service import CreateKeyRingRequest -from .types.service import DecryptRequest -from .types.service import DecryptResponse -from .types.service import DestroyCryptoKeyVersionRequest -from .types.service import Digest -from .types.service import EncryptRequest -from .types.service import EncryptResponse -from .types.service import GenerateRandomBytesRequest -from .types.service import GenerateRandomBytesResponse -from .types.service import GetCryptoKeyRequest -from .types.service import GetCryptoKeyVersionRequest -from .types.service import GetImportJobRequest -from .types.service import GetKeyRingRequest -from .types.service import GetPublicKeyRequest -from .types.service import ImportCryptoKeyVersionRequest -from .types.service import ListCryptoKeysRequest -from .types.service import ListCryptoKeysResponse -from .types.service import ListCryptoKeyVersionsRequest -from .types.service import ListCryptoKeyVersionsResponse -from .types.service import ListImportJobsRequest -from .types.service import ListImportJobsResponse -from .types.service import ListKeyRingsRequest -from .types.service import ListKeyRingsResponse -from .types.service import LocationMetadata -from .types.service import MacSignRequest -from .types.service import MacSignResponse -from .types.service import MacVerifyRequest -from .types.service import MacVerifyResponse -from .types.service import RawDecryptRequest -from .types.service import RawDecryptResponse -from .types.service import RawEncryptRequest -from .types.service import RawEncryptResponse -from .types.service import RestoreCryptoKeyVersionRequest -from .types.service import UpdateCryptoKeyPrimaryVersionRequest -from .types.service import UpdateCryptoKeyRequest -from .types.service import UpdateCryptoKeyVersionRequest - -__all__ = ( - 'AutokeyAdminAsyncClient', - 'AutokeyAsyncClient', - 'EkmServiceAsyncClient', - 'KeyManagementServiceAsyncClient', -'AccessReason', -'AsymmetricDecryptRequest', -'AsymmetricDecryptResponse', -'AsymmetricSignRequest', -'AsymmetricSignResponse', -'AutokeyAdminClient', -'AutokeyClient', -'AutokeyConfig', -'Certificate', -'CreateCryptoKeyRequest', -'CreateCryptoKeyVersionRequest', -'CreateEkmConnectionRequest', -'CreateImportJobRequest', -'CreateKeyHandleMetadata', -'CreateKeyHandleRequest', -'CreateKeyRingRequest', -'CryptoKey', -'CryptoKeyVersion', -'CryptoKeyVersionTemplate', -'DecryptRequest', -'DecryptResponse', -'DestroyCryptoKeyVersionRequest', -'Digest', -'EkmConfig', -'EkmConnection', -'EkmServiceClient', -'EncryptRequest', -'EncryptResponse', -'ExternalProtectionLevelOptions', -'GenerateRandomBytesRequest', -'GenerateRandomBytesResponse', -'GetAutokeyConfigRequest', -'GetCryptoKeyRequest', -'GetCryptoKeyVersionRequest', -'GetEkmConfigRequest', -'GetEkmConnectionRequest', -'GetImportJobRequest', -'GetKeyHandleRequest', -'GetKeyRingRequest', -'GetPublicKeyRequest', -'ImportCryptoKeyVersionRequest', -'ImportJob', -'KeyAccessJustificationsPolicy', -'KeyHandle', -'KeyManagementServiceClient', -'KeyOperationAttestation', -'KeyRing', -'ListCryptoKeyVersionsRequest', -'ListCryptoKeyVersionsResponse', -'ListCryptoKeysRequest', -'ListCryptoKeysResponse', -'ListEkmConnectionsRequest', -'ListEkmConnectionsResponse', -'ListImportJobsRequest', -'ListImportJobsResponse', -'ListKeyHandlesRequest', -'ListKeyHandlesResponse', -'ListKeyRingsRequest', -'ListKeyRingsResponse', -'LocationMetadata', -'MacSignRequest', -'MacSignResponse', -'MacVerifyRequest', -'MacVerifyResponse', -'ProtectionLevel', -'PublicKey', -'RawDecryptRequest', -'RawDecryptResponse', -'RawEncryptRequest', -'RawEncryptResponse', -'RestoreCryptoKeyVersionRequest', -'ShowEffectiveAutokeyConfigRequest', -'ShowEffectiveAutokeyConfigResponse', -'UpdateAutokeyConfigRequest', -'UpdateCryptoKeyPrimaryVersionRequest', -'UpdateCryptoKeyRequest', -'UpdateCryptoKeyVersionRequest', -'UpdateEkmConfigRequest', -'UpdateEkmConnectionRequest', -'VerifyConnectivityRequest', -'VerifyConnectivityResponse', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_metadata.json b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_metadata.json deleted file mode 100644 index 4d760054fd94..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_metadata.json +++ /dev/null @@ -1,700 +0,0 @@ - { - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", - "language": "python", - "libraryPackage": "google.cloud.kms_v1", - "protoPackage": "google.cloud.kms.v1", - "schema": "1.0", - "services": { - "Autokey": { - "clients": { - "grpc": { - "libraryClient": "AutokeyClient", - "rpcs": { - "CreateKeyHandle": { - "methods": [ - "create_key_handle" - ] - }, - "GetKeyHandle": { - "methods": [ - "get_key_handle" - ] - }, - "ListKeyHandles": { - "methods": [ - "list_key_handles" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AutokeyAsyncClient", - "rpcs": { - "CreateKeyHandle": { - "methods": [ - "create_key_handle" - ] - }, - "GetKeyHandle": { - "methods": [ - "get_key_handle" - ] - }, - "ListKeyHandles": { - "methods": [ - "list_key_handles" - ] - } - } - }, - "rest": { - "libraryClient": "AutokeyClient", - "rpcs": { - "CreateKeyHandle": { - "methods": [ - "create_key_handle" - ] - }, - "GetKeyHandle": { - "methods": [ - "get_key_handle" - ] - }, - "ListKeyHandles": { - "methods": [ - "list_key_handles" - ] - } - } - } - } - }, - "AutokeyAdmin": { - "clients": { - "grpc": { - "libraryClient": "AutokeyAdminClient", - "rpcs": { - "GetAutokeyConfig": { - "methods": [ - "get_autokey_config" - ] - }, - "ShowEffectiveAutokeyConfig": { - "methods": [ - "show_effective_autokey_config" - ] - }, - "UpdateAutokeyConfig": { - "methods": [ - "update_autokey_config" - ] - } - } - }, - "grpc-async": { - "libraryClient": "AutokeyAdminAsyncClient", - "rpcs": { - "GetAutokeyConfig": { - "methods": [ - "get_autokey_config" - ] - }, - "ShowEffectiveAutokeyConfig": { - "methods": [ - "show_effective_autokey_config" - ] - }, - "UpdateAutokeyConfig": { - "methods": [ - "update_autokey_config" - ] - } - } - }, - "rest": { - "libraryClient": "AutokeyAdminClient", - "rpcs": { - "GetAutokeyConfig": { - "methods": [ - "get_autokey_config" - ] - }, - "ShowEffectiveAutokeyConfig": { - "methods": [ - "show_effective_autokey_config" - ] - }, - "UpdateAutokeyConfig": { - "methods": [ - "update_autokey_config" - ] - } - } - } - } - }, - "EkmService": { - "clients": { - "grpc": { - "libraryClient": "EkmServiceClient", - "rpcs": { - "CreateEkmConnection": { - "methods": [ - "create_ekm_connection" - ] - }, - "GetEkmConfig": { - "methods": [ - "get_ekm_config" - ] - }, - "GetEkmConnection": { - "methods": [ - "get_ekm_connection" - ] - }, - "ListEkmConnections": { - "methods": [ - "list_ekm_connections" - ] - }, - "UpdateEkmConfig": { - "methods": [ - "update_ekm_config" - ] - }, - "UpdateEkmConnection": { - "methods": [ - "update_ekm_connection" - ] - }, - "VerifyConnectivity": { - "methods": [ - "verify_connectivity" - ] - } - } - }, - "grpc-async": { - "libraryClient": "EkmServiceAsyncClient", - "rpcs": { - "CreateEkmConnection": { - "methods": [ - "create_ekm_connection" - ] - }, - "GetEkmConfig": { - "methods": [ - "get_ekm_config" - ] - }, - "GetEkmConnection": { - "methods": [ - "get_ekm_connection" - ] - }, - "ListEkmConnections": { - "methods": [ - "list_ekm_connections" - ] - }, - "UpdateEkmConfig": { - "methods": [ - "update_ekm_config" - ] - }, - "UpdateEkmConnection": { - "methods": [ - "update_ekm_connection" - ] - }, - "VerifyConnectivity": { - "methods": [ - "verify_connectivity" - ] - } - } - }, - "rest": { - "libraryClient": "EkmServiceClient", - "rpcs": { - "CreateEkmConnection": { - "methods": [ - "create_ekm_connection" - ] - }, - "GetEkmConfig": { - "methods": [ - "get_ekm_config" - ] - }, - "GetEkmConnection": { - "methods": [ - "get_ekm_connection" - ] - }, - "ListEkmConnections": { - "methods": [ - "list_ekm_connections" - ] - }, - "UpdateEkmConfig": { - "methods": [ - "update_ekm_config" - ] - }, - "UpdateEkmConnection": { - "methods": [ - "update_ekm_connection" - ] - }, - "VerifyConnectivity": { - "methods": [ - "verify_connectivity" - ] - } - } - } - } - }, - "KeyManagementService": { - "clients": { - "grpc": { - "libraryClient": "KeyManagementServiceClient", - "rpcs": { - "AsymmetricDecrypt": { - "methods": [ - "asymmetric_decrypt" - ] - }, - "AsymmetricSign": { - "methods": [ - "asymmetric_sign" - ] - }, - "CreateCryptoKey": { - "methods": [ - "create_crypto_key" - ] - }, - "CreateCryptoKeyVersion": { - "methods": [ - "create_crypto_key_version" - ] - }, - "CreateImportJob": { - "methods": [ - "create_import_job" - ] - }, - "CreateKeyRing": { - "methods": [ - "create_key_ring" - ] - }, - "Decrypt": { - "methods": [ - "decrypt" - ] - }, - "DestroyCryptoKeyVersion": { - "methods": [ - "destroy_crypto_key_version" - ] - }, - "Encrypt": { - "methods": [ - "encrypt" - ] - }, - "GenerateRandomBytes": { - "methods": [ - "generate_random_bytes" - ] - }, - "GetCryptoKey": { - "methods": [ - "get_crypto_key" - ] - }, - "GetCryptoKeyVersion": { - "methods": [ - "get_crypto_key_version" - ] - }, - "GetImportJob": { - "methods": [ - "get_import_job" - ] - }, - "GetKeyRing": { - "methods": [ - "get_key_ring" - ] - }, - "GetPublicKey": { - "methods": [ - "get_public_key" - ] - }, - "ImportCryptoKeyVersion": { - "methods": [ - "import_crypto_key_version" - ] - }, - "ListCryptoKeyVersions": { - "methods": [ - "list_crypto_key_versions" - ] - }, - "ListCryptoKeys": { - "methods": [ - "list_crypto_keys" - ] - }, - "ListImportJobs": { - "methods": [ - "list_import_jobs" - ] - }, - "ListKeyRings": { - "methods": [ - "list_key_rings" - ] - }, - "MacSign": { - "methods": [ - "mac_sign" - ] - }, - "MacVerify": { - "methods": [ - "mac_verify" - ] - }, - "RawDecrypt": { - "methods": [ - "raw_decrypt" - ] - }, - "RawEncrypt": { - "methods": [ - "raw_encrypt" - ] - }, - "RestoreCryptoKeyVersion": { - "methods": [ - "restore_crypto_key_version" - ] - }, - "UpdateCryptoKey": { - "methods": [ - "update_crypto_key" - ] - }, - "UpdateCryptoKeyPrimaryVersion": { - "methods": [ - "update_crypto_key_primary_version" - ] - }, - "UpdateCryptoKeyVersion": { - "methods": [ - "update_crypto_key_version" - ] - } - } - }, - "grpc-async": { - "libraryClient": "KeyManagementServiceAsyncClient", - "rpcs": { - "AsymmetricDecrypt": { - "methods": [ - "asymmetric_decrypt" - ] - }, - "AsymmetricSign": { - "methods": [ - "asymmetric_sign" - ] - }, - "CreateCryptoKey": { - "methods": [ - "create_crypto_key" - ] - }, - "CreateCryptoKeyVersion": { - "methods": [ - "create_crypto_key_version" - ] - }, - "CreateImportJob": { - "methods": [ - "create_import_job" - ] - }, - "CreateKeyRing": { - "methods": [ - "create_key_ring" - ] - }, - "Decrypt": { - "methods": [ - "decrypt" - ] - }, - "DestroyCryptoKeyVersion": { - "methods": [ - "destroy_crypto_key_version" - ] - }, - "Encrypt": { - "methods": [ - "encrypt" - ] - }, - "GenerateRandomBytes": { - "methods": [ - "generate_random_bytes" - ] - }, - "GetCryptoKey": { - "methods": [ - "get_crypto_key" - ] - }, - "GetCryptoKeyVersion": { - "methods": [ - "get_crypto_key_version" - ] - }, - "GetImportJob": { - "methods": [ - "get_import_job" - ] - }, - "GetKeyRing": { - "methods": [ - "get_key_ring" - ] - }, - "GetPublicKey": { - "methods": [ - "get_public_key" - ] - }, - "ImportCryptoKeyVersion": { - "methods": [ - "import_crypto_key_version" - ] - }, - "ListCryptoKeyVersions": { - "methods": [ - "list_crypto_key_versions" - ] - }, - "ListCryptoKeys": { - "methods": [ - "list_crypto_keys" - ] - }, - "ListImportJobs": { - "methods": [ - "list_import_jobs" - ] - }, - "ListKeyRings": { - "methods": [ - "list_key_rings" - ] - }, - "MacSign": { - "methods": [ - "mac_sign" - ] - }, - "MacVerify": { - "methods": [ - "mac_verify" - ] - }, - "RawDecrypt": { - "methods": [ - "raw_decrypt" - ] - }, - "RawEncrypt": { - "methods": [ - "raw_encrypt" - ] - }, - "RestoreCryptoKeyVersion": { - "methods": [ - "restore_crypto_key_version" - ] - }, - "UpdateCryptoKey": { - "methods": [ - "update_crypto_key" - ] - }, - "UpdateCryptoKeyPrimaryVersion": { - "methods": [ - "update_crypto_key_primary_version" - ] - }, - "UpdateCryptoKeyVersion": { - "methods": [ - "update_crypto_key_version" - ] - } - } - }, - "rest": { - "libraryClient": "KeyManagementServiceClient", - "rpcs": { - "AsymmetricDecrypt": { - "methods": [ - "asymmetric_decrypt" - ] - }, - "AsymmetricSign": { - "methods": [ - "asymmetric_sign" - ] - }, - "CreateCryptoKey": { - "methods": [ - "create_crypto_key" - ] - }, - "CreateCryptoKeyVersion": { - "methods": [ - "create_crypto_key_version" - ] - }, - "CreateImportJob": { - "methods": [ - "create_import_job" - ] - }, - "CreateKeyRing": { - "methods": [ - "create_key_ring" - ] - }, - "Decrypt": { - "methods": [ - "decrypt" - ] - }, - "DestroyCryptoKeyVersion": { - "methods": [ - "destroy_crypto_key_version" - ] - }, - "Encrypt": { - "methods": [ - "encrypt" - ] - }, - "GenerateRandomBytes": { - "methods": [ - "generate_random_bytes" - ] - }, - "GetCryptoKey": { - "methods": [ - "get_crypto_key" - ] - }, - "GetCryptoKeyVersion": { - "methods": [ - "get_crypto_key_version" - ] - }, - "GetImportJob": { - "methods": [ - "get_import_job" - ] - }, - "GetKeyRing": { - "methods": [ - "get_key_ring" - ] - }, - "GetPublicKey": { - "methods": [ - "get_public_key" - ] - }, - "ImportCryptoKeyVersion": { - "methods": [ - "import_crypto_key_version" - ] - }, - "ListCryptoKeyVersions": { - "methods": [ - "list_crypto_key_versions" - ] - }, - "ListCryptoKeys": { - "methods": [ - "list_crypto_keys" - ] - }, - "ListImportJobs": { - "methods": [ - "list_import_jobs" - ] - }, - "ListKeyRings": { - "methods": [ - "list_key_rings" - ] - }, - "MacSign": { - "methods": [ - "mac_sign" - ] - }, - "MacVerify": { - "methods": [ - "mac_verify" - ] - }, - "RawDecrypt": { - "methods": [ - "raw_decrypt" - ] - }, - "RawEncrypt": { - "methods": [ - "raw_encrypt" - ] - }, - "RestoreCryptoKeyVersion": { - "methods": [ - "restore_crypto_key_version" - ] - }, - "UpdateCryptoKey": { - "methods": [ - "update_crypto_key" - ] - }, - "UpdateCryptoKeyPrimaryVersion": { - "methods": [ - "update_crypto_key_primary_version" - ] - }, - "UpdateCryptoKeyVersion": { - "methods": [ - "update_crypto_key_version" - ] - } - } - } - } - } - } -} diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_version.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_version.py deleted file mode 100644 index 558c8aab67c5..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/gapic_version.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -__version__ = "0.0.0" # {x-release-please-version} diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/py.typed b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/py.typed deleted file mode 100644 index 3720b5f23ae9..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-kms package uses inline types. diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/__init__.py deleted file mode 100644 index 8f6cf068242c..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/__init__.py deleted file mode 100644 index 4875c51e6dea..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import AutokeyClient -from .async_client import AutokeyAsyncClient - -__all__ = ( - 'AutokeyClient', - 'AutokeyAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/async_client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/async_client.py deleted file mode 100644 index e8ffd3bdf912..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/async_client.py +++ /dev/null @@ -1,1074 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.kms_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.kms_v1.services.autokey import pagers -from google.cloud.kms_v1.types import autokey -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import AutokeyTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AutokeyGrpcAsyncIOTransport -from .client import AutokeyClient - - -class AutokeyAsyncClient: - """Provides interfaces for using `Cloud KMS - Autokey `__ to provision - new [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer - Managed Encryption Key (CMEK) use, on-demand. To support certain - client tooling, this feature is modeled around a - [KeyHandle][google.cloud.kms.v1.KeyHandle] resource: creating a - [KeyHandle][google.cloud.kms.v1.KeyHandle] in a resource project and - given location triggers Cloud KMS Autokey to provision a - [CryptoKey][google.cloud.kms.v1.CryptoKey] in the configured key - project and the same location. - - Prior to use in a given resource project, - [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig] - should have been called on an ancestor folder, setting the key - project where Cloud KMS Autokey should create new - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. See documentation for - additional prerequisites. To check what key project, if any, is - currently configured on a resource project's ancestor folder, see - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - """ - - _client: AutokeyClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AutokeyClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AutokeyClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AutokeyClient._DEFAULT_UNIVERSE - - crypto_key_path = staticmethod(AutokeyClient.crypto_key_path) - parse_crypto_key_path = staticmethod(AutokeyClient.parse_crypto_key_path) - key_handle_path = staticmethod(AutokeyClient.key_handle_path) - parse_key_handle_path = staticmethod(AutokeyClient.parse_key_handle_path) - common_billing_account_path = staticmethod(AutokeyClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AutokeyClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AutokeyClient.common_folder_path) - parse_common_folder_path = staticmethod(AutokeyClient.parse_common_folder_path) - common_organization_path = staticmethod(AutokeyClient.common_organization_path) - parse_common_organization_path = staticmethod(AutokeyClient.parse_common_organization_path) - common_project_path = staticmethod(AutokeyClient.common_project_path) - parse_common_project_path = staticmethod(AutokeyClient.parse_common_project_path) - common_location_path = staticmethod(AutokeyClient.common_location_path) - parse_common_location_path = staticmethod(AutokeyClient.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: - AutokeyAsyncClient: The constructed client. - """ - return AutokeyClient.from_service_account_info.__func__(AutokeyAsyncClient, 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: - AutokeyAsyncClient: The constructed client. - """ - return AutokeyClient.from_service_account_file.__func__(AutokeyAsyncClient, 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 AutokeyClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AutokeyTransport: - """Returns the transport used by the client instance. - - Returns: - AutokeyTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = AutokeyClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AutokeyTransport, Callable[..., AutokeyTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the autokey async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AutokeyTransport,Callable[..., AutokeyTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the AutokeyTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = AutokeyClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def create_key_handle(self, - request: Optional[Union[autokey.CreateKeyHandleRequest, dict]] = None, - *, - parent: Optional[str] = None, - key_handle: Optional[autokey.KeyHandle] = None, - key_handle_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new [KeyHandle][google.cloud.kms.v1.KeyHandle], - triggering the provisioning of a new - [CryptoKey][google.cloud.kms.v1.CryptoKey] for CMEK use with the - given resource type in the configured key project and the same - location. [GetOperation][Operations.GetOperation] should be used - to resolve the resulting long-running operation and get the - resulting [KeyHandle][google.cloud.kms.v1.KeyHandle] and - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_create_key_handle(): - # Create a client - client = kms_v1.AutokeyAsyncClient() - - # Initialize request argument(s) - key_handle = kms_v1.KeyHandle() - key_handle.resource_type_selector = "resource_type_selector_value" - - request = kms_v1.CreateKeyHandleRequest( - parent="parent_value", - key_handle=key_handle, - ) - - # Make the request - operation = client.create_key_handle(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.CreateKeyHandleRequest, dict]]): - The request object. Request message for - [Autokey.CreateKeyHandle][google.cloud.kms.v1.Autokey.CreateKeyHandle]. - parent (:class:`str`): - Required. Name of the resource project and location to - create the [KeyHandle][google.cloud.kms.v1.KeyHandle] - in, e.g. ``projects/{PROJECT_ID}/locations/{LOCATION}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_handle (:class:`google.cloud.kms_v1.types.KeyHandle`): - Required. [KeyHandle][google.cloud.kms.v1.KeyHandle] to - create. - - This corresponds to the ``key_handle`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_handle_id (:class:`str`): - Optional. Id of the - [KeyHandle][google.cloud.kms.v1.KeyHandle]. Must be - unique to the resource project and location. If not - provided by the caller, a new UUID is used. - - This corresponds to the ``key_handle_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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.kms_v1.types.KeyHandle` Resource-oriented representation of a request to Cloud KMS Autokey and the - resulting provisioning of a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, key_handle, key_handle_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey.CreateKeyHandleRequest): - request = autokey.CreateKeyHandleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if key_handle is not None: - request.key_handle = key_handle - if key_handle_id is not None: - request.key_handle_id = key_handle_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_key_handle] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - autokey.KeyHandle, - metadata_type=autokey.CreateKeyHandleMetadata, - ) - - # Done; return the response. - return response - - async def get_key_handle(self, - request: Optional[Union[autokey.GetKeyHandleRequest, 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]] = (), - ) -> autokey.KeyHandle: - r"""Returns the [KeyHandle][google.cloud.kms.v1.KeyHandle]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_get_key_handle(): - # Create a client - client = kms_v1.AutokeyAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetKeyHandleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_key_handle(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.GetKeyHandleRequest, dict]]): - The request object. Request message for - [GetKeyHandle][google.cloud.kms.v1.Autokey.GetKeyHandle]. - name (:class:`str`): - Required. Name of the - [KeyHandle][google.cloud.kms.v1.KeyHandle] resource, - e.g. - ``projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.KeyHandle: - Resource-oriented representation of a request to Cloud KMS Autokey and the - resulting provisioning of a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey.GetKeyHandleRequest): - request = autokey.GetKeyHandleRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_key_handle] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_key_handles(self, - request: Optional[Union[autokey.ListKeyHandlesRequest, 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.ListKeyHandlesAsyncPager: - r"""Lists [KeyHandles][google.cloud.kms.v1.KeyHandle]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_list_key_handles(): - # Create a client - client = kms_v1.AutokeyAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListKeyHandlesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_key_handles(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.ListKeyHandlesRequest, dict]]): - The request object. Request message for - [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. - parent (:class:`str`): - Required. Name of the resource project and location from - which to list - [KeyHandles][google.cloud.kms.v1.KeyHandle], e.g. - ``projects/{PROJECT_ID}/locations/{LOCATION}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.services.autokey.pagers.ListKeyHandlesAsyncPager: - Response message for - [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey.ListKeyHandlesRequest): - request = autokey.ListKeyHandlesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_key_handles] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListKeyHandlesAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_location] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_locations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does - not have a policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified permissions against the IAM access control - policy for a function. - - If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~iam_policy_pb2.PolicyTestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "AutokeyAsyncClient": - 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__ = ( - "AutokeyAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/client.py deleted file mode 100644 index 01dde42c7d5a..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/client.py +++ /dev/null @@ -1,1423 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.kms_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.kms_v1.services.autokey import pagers -from google.cloud.kms_v1.types import autokey -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .transports.base import AutokeyTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AutokeyGrpcTransport -from .transports.grpc_asyncio import AutokeyGrpcAsyncIOTransport -from .transports.rest import AutokeyRestTransport - - -class AutokeyClientMeta(type): - """Metaclass for the Autokey 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[AutokeyTransport]] - _transport_registry["grpc"] = AutokeyGrpcTransport - _transport_registry["grpc_asyncio"] = AutokeyGrpcAsyncIOTransport - _transport_registry["rest"] = AutokeyRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AutokeyTransport]: - """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 AutokeyClient(metaclass=AutokeyClientMeta): - """Provides interfaces for using `Cloud KMS - Autokey `__ to provision - new [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer - Managed Encryption Key (CMEK) use, on-demand. To support certain - client tooling, this feature is modeled around a - [KeyHandle][google.cloud.kms.v1.KeyHandle] resource: creating a - [KeyHandle][google.cloud.kms.v1.KeyHandle] in a resource project and - given location triggers Cloud KMS Autokey to provision a - [CryptoKey][google.cloud.kms.v1.CryptoKey] in the configured key - project and the same location. - - Prior to use in a given resource project, - [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig] - should have been called on an ancestor folder, setting the key - project where Cloud KMS Autokey should create new - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. See documentation for - additional prerequisites. To check what key project, if any, is - currently configured on a resource project's ancestor folder, see - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "cloudkms.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "cloudkms.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AutokeyClient: 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: - AutokeyClient: 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) -> AutokeyTransport: - """Returns the transport used by the client instance. - - Returns: - AutokeyTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: - """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - - @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: - """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def key_handle_path(project: str,location: str,key_handle: str,) -> str: - """Returns a fully-qualified key_handle string.""" - return "projects/{project}/locations/{location}/keyHandles/{key_handle}".format(project=project, location=location, key_handle=key_handle, ) - - @staticmethod - def parse_key_handle_path(path: str) -> Dict[str,str]: - """Parses a key_handle path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyHandles/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = AutokeyClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AutokeyClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = AutokeyClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AutokeyTransport, Callable[..., AutokeyTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the autokey client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AutokeyTransport,Callable[..., AutokeyTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the AutokeyTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AutokeyClient._read_environment_variables() - self._client_cert_source = AutokeyClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AutokeyClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, AutokeyTransport) - if transport_provided: - # transport is a AutokeyTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(AutokeyTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AutokeyClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[AutokeyTransport], Callable[..., AutokeyTransport]] = ( - AutokeyClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AutokeyTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def create_key_handle(self, - request: Optional[Union[autokey.CreateKeyHandleRequest, dict]] = None, - *, - parent: Optional[str] = None, - key_handle: Optional[autokey.KeyHandle] = None, - key_handle_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Creates a new [KeyHandle][google.cloud.kms.v1.KeyHandle], - triggering the provisioning of a new - [CryptoKey][google.cloud.kms.v1.CryptoKey] for CMEK use with the - given resource type in the configured key project and the same - location. [GetOperation][Operations.GetOperation] should be used - to resolve the resulting long-running operation and get the - resulting [KeyHandle][google.cloud.kms.v1.KeyHandle] and - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_create_key_handle(): - # Create a client - client = kms_v1.AutokeyClient() - - # Initialize request argument(s) - key_handle = kms_v1.KeyHandle() - key_handle.resource_type_selector = "resource_type_selector_value" - - request = kms_v1.CreateKeyHandleRequest( - parent="parent_value", - key_handle=key_handle, - ) - - # Make the request - operation = client.create_key_handle(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.CreateKeyHandleRequest, dict]): - The request object. Request message for - [Autokey.CreateKeyHandle][google.cloud.kms.v1.Autokey.CreateKeyHandle]. - parent (str): - Required. Name of the resource project and location to - create the [KeyHandle][google.cloud.kms.v1.KeyHandle] - in, e.g. ``projects/{PROJECT_ID}/locations/{LOCATION}``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_handle (google.cloud.kms_v1.types.KeyHandle): - Required. [KeyHandle][google.cloud.kms.v1.KeyHandle] to - create. - - This corresponds to the ``key_handle`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_handle_id (str): - Optional. Id of the - [KeyHandle][google.cloud.kms.v1.KeyHandle]. Must be - unique to the resource project and location. If not - provided by the caller, a new UUID is used. - - This corresponds to the ``key_handle_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be :class:`google.cloud.kms_v1.types.KeyHandle` Resource-oriented representation of a request to Cloud KMS Autokey and the - resulting provisioning of a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, key_handle, key_handle_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey.CreateKeyHandleRequest): - request = autokey.CreateKeyHandleRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if key_handle is not None: - request.key_handle = key_handle - if key_handle_id is not None: - request.key_handle_id = key_handle_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_key_handle] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - autokey.KeyHandle, - metadata_type=autokey.CreateKeyHandleMetadata, - ) - - # Done; return the response. - return response - - def get_key_handle(self, - request: Optional[Union[autokey.GetKeyHandleRequest, 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]] = (), - ) -> autokey.KeyHandle: - r"""Returns the [KeyHandle][google.cloud.kms.v1.KeyHandle]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_get_key_handle(): - # Create a client - client = kms_v1.AutokeyClient() - - # Initialize request argument(s) - request = kms_v1.GetKeyHandleRequest( - name="name_value", - ) - - # Make the request - response = client.get_key_handle(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.GetKeyHandleRequest, dict]): - The request object. Request message for - [GetKeyHandle][google.cloud.kms.v1.Autokey.GetKeyHandle]. - name (str): - Required. Name of the - [KeyHandle][google.cloud.kms.v1.KeyHandle] resource, - e.g. - ``projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}``. - - 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.kms_v1.types.KeyHandle: - Resource-oriented representation of a request to Cloud KMS Autokey and the - resulting provisioning of a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey.GetKeyHandleRequest): - request = autokey.GetKeyHandleRequest(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_key_handle] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_key_handles(self, - request: Optional[Union[autokey.ListKeyHandlesRequest, 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.ListKeyHandlesPager: - r"""Lists [KeyHandles][google.cloud.kms.v1.KeyHandle]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_list_key_handles(): - # Create a client - client = kms_v1.AutokeyClient() - - # Initialize request argument(s) - request = kms_v1.ListKeyHandlesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_key_handles(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.ListKeyHandlesRequest, dict]): - The request object. Request message for - [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. - parent (str): - Required. Name of the resource project and location from - which to list - [KeyHandles][google.cloud.kms.v1.KeyHandle], e.g. - ``projects/{PROJECT_ID}/locations/{LOCATION}``. - - 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.kms_v1.services.autokey.pagers.ListKeyHandlesPager: - Response message for - [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey.ListKeyHandlesRequest): - request = autokey.ListKeyHandlesRequest(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_key_handles] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListKeyHandlesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AutokeyClient": - 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 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 = self._transport._wrapped_methods[self._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_location] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_locations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AutokeyClient", -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/pagers.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/pagers.py deleted file mode 100644 index 774a3ee84746..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.cloud.kms_v1.types import autokey - - -class ListKeyHandlesPager: - """A pager for iterating through ``list_key_handles`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListKeyHandlesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``key_handles`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListKeyHandles`` requests and continue to iterate - through the ``key_handles`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListKeyHandlesResponse` - 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[..., autokey.ListKeyHandlesResponse], - request: autokey.ListKeyHandlesRequest, - response: autokey.ListKeyHandlesResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListKeyHandlesRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListKeyHandlesResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = autokey.ListKeyHandlesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[autokey.ListKeyHandlesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[autokey.KeyHandle]: - for page in self.pages: - yield from page.key_handles - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListKeyHandlesAsyncPager: - """A pager for iterating through ``list_key_handles`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListKeyHandlesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``key_handles`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListKeyHandles`` requests and continue to iterate - through the ``key_handles`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListKeyHandlesResponse` - 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[autokey.ListKeyHandlesResponse]], - request: autokey.ListKeyHandlesRequest, - response: autokey.ListKeyHandlesResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListKeyHandlesRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListKeyHandlesResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = autokey.ListKeyHandlesRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[autokey.ListKeyHandlesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[autokey.KeyHandle]: - async def async_generator(): - async for page in self.pages: - for response in page.key_handles: - 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-kms/v1/google/cloud/kms_v1/services/autokey/transports/README.rst b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/README.rst deleted file mode 100644 index e6b77aacde54..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AutokeyTransport` is the ABC for all transports. -- public child `AutokeyGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AutokeyGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAutokeyRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AutokeyRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/__init__.py deleted file mode 100644 index c53d2840ddd7..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import AutokeyTransport -from .grpc import AutokeyGrpcTransport -from .grpc_asyncio import AutokeyGrpcAsyncIOTransport -from .rest import AutokeyRestTransport -from .rest import AutokeyRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AutokeyTransport]] -_transport_registry['grpc'] = AutokeyGrpcTransport -_transport_registry['grpc_asyncio'] = AutokeyGrpcAsyncIOTransport -_transport_registry['rest'] = AutokeyRestTransport - -__all__ = ( - 'AutokeyTransport', - 'AutokeyGrpcTransport', - 'AutokeyGrpcAsyncIOTransport', - 'AutokeyRestTransport', - 'AutokeyRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/base.py deleted file mode 100644 index d5cb99f09a57..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/base.py +++ /dev/null @@ -1,298 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.kms_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.kms_v1.types import autokey -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AutokeyTransport(abc.ABC): - """Abstract transport class for Autokey.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', - ) - - DEFAULT_HOST: str = 'cloudkms.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_key_handle: gapic_v1.method.wrap_method( - self.create_key_handle, - default_timeout=60.0, - client_info=client_info, - ), - self.get_key_handle: gapic_v1.method.wrap_method( - self.get_key_handle, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_key_handles: gapic_v1.method.wrap_method( - self.list_key_handles, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - } - - 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_key_handle(self) -> Callable[ - [autokey.CreateKeyHandleRequest], - Union[ - operations_pb2.Operation, - Awaitable[operations_pb2.Operation] - ]]: - raise NotImplementedError() - - @property - def get_key_handle(self) -> Callable[ - [autokey.GetKeyHandleRequest], - Union[ - autokey.KeyHandle, - Awaitable[autokey.KeyHandle] - ]]: - raise NotImplementedError() - - @property - def list_key_handles(self) -> Callable[ - [autokey.ListKeyHandlesRequest], - Union[ - autokey.ListKeyHandlesResponse, - Awaitable[autokey.ListKeyHandlesResponse] - ]]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AutokeyTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc.py deleted file mode 100644 index fff0485d8ea3..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc.py +++ /dev/null @@ -1,502 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -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.kms_v1.types import autokey -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import AutokeyTransport, DEFAULT_CLIENT_INFO - - -class AutokeyGrpcTransport(AutokeyTransport): - """gRPC backend transport for Autokey. - - Provides interfaces for using `Cloud KMS - Autokey `__ to provision - new [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer - Managed Encryption Key (CMEK) use, on-demand. To support certain - client tooling, this feature is modeled around a - [KeyHandle][google.cloud.kms.v1.KeyHandle] resource: creating a - [KeyHandle][google.cloud.kms.v1.KeyHandle] in a resource project and - given location triggers Cloud KMS Autokey to provision a - [CryptoKey][google.cloud.kms.v1.CryptoKey] in the configured key - project and the same location. - - Prior to use in a given resource project, - [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig] - should have been called on an ancestor folder, setting the key - project where Cloud KMS Autokey should create new - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. See documentation for - additional prerequisites. To check what key project, if any, is - currently configured on a resource project's ancestor folder, see - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - - 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 = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudkms.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_key_handle(self) -> Callable[ - [autokey.CreateKeyHandleRequest], - operations_pb2.Operation]: - r"""Return a callable for the create key handle method over gRPC. - - Creates a new [KeyHandle][google.cloud.kms.v1.KeyHandle], - triggering the provisioning of a new - [CryptoKey][google.cloud.kms.v1.CryptoKey] for CMEK use with the - given resource type in the configured key project and the same - location. [GetOperation][Operations.GetOperation] should be used - to resolve the resulting long-running operation and get the - resulting [KeyHandle][google.cloud.kms.v1.KeyHandle] and - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.CreateKeyHandleRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_key_handle' not in self._stubs: - self._stubs['create_key_handle'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.Autokey/CreateKeyHandle', - request_serializer=autokey.CreateKeyHandleRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_key_handle'] - - @property - def get_key_handle(self) -> Callable[ - [autokey.GetKeyHandleRequest], - autokey.KeyHandle]: - r"""Return a callable for the get key handle method over gRPC. - - Returns the [KeyHandle][google.cloud.kms.v1.KeyHandle]. - - Returns: - Callable[[~.GetKeyHandleRequest], - ~.KeyHandle]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_key_handle' not in self._stubs: - self._stubs['get_key_handle'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.Autokey/GetKeyHandle', - request_serializer=autokey.GetKeyHandleRequest.serialize, - response_deserializer=autokey.KeyHandle.deserialize, - ) - return self._stubs['get_key_handle'] - - @property - def list_key_handles(self) -> Callable[ - [autokey.ListKeyHandlesRequest], - autokey.ListKeyHandlesResponse]: - r"""Return a callable for the list key handles method over gRPC. - - Lists [KeyHandles][google.cloud.kms.v1.KeyHandle]. - - Returns: - Callable[[~.ListKeyHandlesRequest], - ~.ListKeyHandlesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_key_handles' not in self._stubs: - self._stubs['list_key_handles'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.Autokey/ListKeyHandles', - request_serializer=autokey.ListKeyHandlesRequest.serialize, - response_deserializer=autokey.ListKeyHandlesResponse.deserialize, - ) - return self._stubs['list_key_handles'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - def close(self): - self.grpc_channel.close() - - @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_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AutokeyGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc_asyncio.py deleted file mode 100644 index 5c98c65a9d14..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/grpc_asyncio.py +++ /dev/null @@ -1,584 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.api_core import operations_v1 -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.kms_v1.types import autokey -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import AutokeyTransport, DEFAULT_CLIENT_INFO -from .grpc import AutokeyGrpcTransport - - -class AutokeyGrpcAsyncIOTransport(AutokeyTransport): - """gRPC AsyncIO backend transport for Autokey. - - Provides interfaces for using `Cloud KMS - Autokey `__ to provision - new [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer - Managed Encryption Key (CMEK) use, on-demand. To support certain - client tooling, this feature is modeled around a - [KeyHandle][google.cloud.kms.v1.KeyHandle] resource: creating a - [KeyHandle][google.cloud.kms.v1.KeyHandle] in a resource project and - given location triggers Cloud KMS Autokey to provision a - [CryptoKey][google.cloud.kms.v1.CryptoKey] in the configured key - project and the same location. - - Prior to use in a given resource project, - [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig] - should have been called on an ancestor folder, setting the key - project where Cloud KMS Autokey should create new - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. See documentation for - additional prerequisites. To check what key project, if any, is - currently configured on a resource project's ancestor folder, see - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - - 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 = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_key_handle(self) -> Callable[ - [autokey.CreateKeyHandleRequest], - Awaitable[operations_pb2.Operation]]: - r"""Return a callable for the create key handle method over gRPC. - - Creates a new [KeyHandle][google.cloud.kms.v1.KeyHandle], - triggering the provisioning of a new - [CryptoKey][google.cloud.kms.v1.CryptoKey] for CMEK use with the - given resource type in the configured key project and the same - location. [GetOperation][Operations.GetOperation] should be used - to resolve the resulting long-running operation and get the - resulting [KeyHandle][google.cloud.kms.v1.KeyHandle] and - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.CreateKeyHandleRequest], - 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_key_handle' not in self._stubs: - self._stubs['create_key_handle'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.Autokey/CreateKeyHandle', - request_serializer=autokey.CreateKeyHandleRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, - ) - return self._stubs['create_key_handle'] - - @property - def get_key_handle(self) -> Callable[ - [autokey.GetKeyHandleRequest], - Awaitable[autokey.KeyHandle]]: - r"""Return a callable for the get key handle method over gRPC. - - Returns the [KeyHandle][google.cloud.kms.v1.KeyHandle]. - - Returns: - Callable[[~.GetKeyHandleRequest], - Awaitable[~.KeyHandle]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_key_handle' not in self._stubs: - self._stubs['get_key_handle'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.Autokey/GetKeyHandle', - request_serializer=autokey.GetKeyHandleRequest.serialize, - response_deserializer=autokey.KeyHandle.deserialize, - ) - return self._stubs['get_key_handle'] - - @property - def list_key_handles(self) -> Callable[ - [autokey.ListKeyHandlesRequest], - Awaitable[autokey.ListKeyHandlesResponse]]: - r"""Return a callable for the list key handles method over gRPC. - - Lists [KeyHandles][google.cloud.kms.v1.KeyHandle]. - - Returns: - Callable[[~.ListKeyHandlesRequest], - Awaitable[~.ListKeyHandlesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_key_handles' not in self._stubs: - self._stubs['list_key_handles'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.Autokey/ListKeyHandles', - request_serializer=autokey.ListKeyHandlesRequest.serialize, - response_deserializer=autokey.ListKeyHandlesResponse.deserialize, - ) - return self._stubs['list_key_handles'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.create_key_handle: self._wrap_method( - self.create_key_handle, - default_timeout=60.0, - client_info=client_info, - ), - self.get_key_handle: self._wrap_method( - self.get_key_handle, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_key_handles: self._wrap_method( - self.list_key_handles, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @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_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'AutokeyGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest.py deleted file mode 100644 index 90947de10822..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest.py +++ /dev/null @@ -1,1119 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.api_core import operations_v1 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.kms_v1.types import autokey -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseAutokeyRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - - -class AutokeyRestInterceptor: - """Interceptor for Autokey. - - 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 AutokeyRestTransport. - - .. code-block:: python - class MyCustomAutokeyInterceptor(AutokeyRestInterceptor): - def pre_create_key_handle(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_key_handle(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_key_handle(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_key_handle(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_key_handles(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_key_handles(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AutokeyRestTransport(interceptor=MyCustomAutokeyInterceptor()) - client = AutokeyClient(transport=transport) - - - """ - def pre_create_key_handle(self, request: autokey.CreateKeyHandleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey.CreateKeyHandleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_key_handle - - Override in a subclass to manipulate the request or metadata - before they are sent to the Autokey server. - """ - return request, metadata - - def post_create_key_handle(self, response: operations_pb2.Operation) -> operations_pb2.Operation: - """Post-rpc interceptor for create_key_handle - - Override in a subclass to manipulate the response - after it is returned by the Autokey server but before - it is returned to user code. - """ - return response - - def pre_get_key_handle(self, request: autokey.GetKeyHandleRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey.GetKeyHandleRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_key_handle - - Override in a subclass to manipulate the request or metadata - before they are sent to the Autokey server. - """ - return request, metadata - - def post_get_key_handle(self, response: autokey.KeyHandle) -> autokey.KeyHandle: - """Post-rpc interceptor for get_key_handle - - Override in a subclass to manipulate the response - after it is returned by the Autokey server but before - it is returned to user code. - """ - return response - - def pre_list_key_handles(self, request: autokey.ListKeyHandlesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey.ListKeyHandlesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_key_handles - - Override in a subclass to manipulate the request or metadata - before they are sent to the Autokey server. - """ - return request, metadata - - def post_list_key_handles(self, response: autokey.ListKeyHandlesResponse) -> autokey.ListKeyHandlesResponse: - """Post-rpc interceptor for list_key_handles - - Override in a subclass to manipulate the response - after it is returned by the Autokey server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the Autokey server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the Autokey server but before - it is returned to user code. - """ - return response - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the Autokey server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the Autokey server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Autokey server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the Autokey server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the Autokey server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the Autokey server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the Autokey server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the Autokey 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 Autokey 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 Autokey server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AutokeyRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AutokeyRestInterceptor - - -class AutokeyRestTransport(_BaseAutokeyRestTransport): - """REST backend synchronous transport for Autokey. - - Provides interfaces for using `Cloud KMS - Autokey `__ to provision - new [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer - Managed Encryption Key (CMEK) use, on-demand. To support certain - client tooling, this feature is modeled around a - [KeyHandle][google.cloud.kms.v1.KeyHandle] resource: creating a - [KeyHandle][google.cloud.kms.v1.KeyHandle] in a resource project and - given location triggers Cloud KMS Autokey to provision a - [CryptoKey][google.cloud.kms.v1.CryptoKey] in the configured key - project and the same location. - - Prior to use in a given resource project, - [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig] - should have been called on an ancestor folder, setting the key - project where Cloud KMS Autokey should create new - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. See documentation for - additional prerequisites. To check what key project, if any, is - currently configured on a resource project's ancestor folder, see - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - - 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 = 'cloudkms.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[AutokeyRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or AutokeyRestInterceptor() - 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.GetOperation': [ - { - '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 _CreateKeyHandle(_BaseAutokeyRestTransport._BaseCreateKeyHandle, AutokeyRestStub): - def __hash__(self): - return hash("AutokeyRestTransport.CreateKeyHandle") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: autokey.CreateKeyHandleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> operations_pb2.Operation: - r"""Call the create key handle method over HTTP. - - Args: - request (~.autokey.CreateKeyHandleRequest): - The request object. Request message for - [Autokey.CreateKeyHandle][google.cloud.kms.v1.Autokey.CreateKeyHandle]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - 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 = _BaseAutokeyRestTransport._BaseCreateKeyHandle._get_http_options() - request, metadata = self._interceptor.pre_create_key_handle(request, metadata) - transcoded_request = _BaseAutokeyRestTransport._BaseCreateKeyHandle._get_transcoded_request(http_options, request) - - body = _BaseAutokeyRestTransport._BaseCreateKeyHandle._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAutokeyRestTransport._BaseCreateKeyHandle._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyRestTransport._CreateKeyHandle._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_key_handle(resp) - return resp - - class _GetKeyHandle(_BaseAutokeyRestTransport._BaseGetKeyHandle, AutokeyRestStub): - def __hash__(self): - return hash("AutokeyRestTransport.GetKeyHandle") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: autokey.GetKeyHandleRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> autokey.KeyHandle: - r"""Call the get key handle method over HTTP. - - Args: - request (~.autokey.GetKeyHandleRequest): - The request object. Request message for - [GetKeyHandle][google.cloud.kms.v1.Autokey.GetKeyHandle]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.autokey.KeyHandle: - Resource-oriented representation of a request to Cloud - KMS Autokey and the resulting provisioning of a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - """ - - http_options = _BaseAutokeyRestTransport._BaseGetKeyHandle._get_http_options() - request, metadata = self._interceptor.pre_get_key_handle(request, metadata) - transcoded_request = _BaseAutokeyRestTransport._BaseGetKeyHandle._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyRestTransport._BaseGetKeyHandle._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyRestTransport._GetKeyHandle._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = autokey.KeyHandle() - pb_resp = autokey.KeyHandle.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_key_handle(resp) - return resp - - class _ListKeyHandles(_BaseAutokeyRestTransport._BaseListKeyHandles, AutokeyRestStub): - def __hash__(self): - return hash("AutokeyRestTransport.ListKeyHandles") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: autokey.ListKeyHandlesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> autokey.ListKeyHandlesResponse: - r"""Call the list key handles method over HTTP. - - Args: - request (~.autokey.ListKeyHandlesRequest): - The request object. Request message for - [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.autokey.ListKeyHandlesResponse: - Response message for - [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. - - """ - - http_options = _BaseAutokeyRestTransport._BaseListKeyHandles._get_http_options() - request, metadata = self._interceptor.pre_list_key_handles(request, metadata) - transcoded_request = _BaseAutokeyRestTransport._BaseListKeyHandles._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyRestTransport._BaseListKeyHandles._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyRestTransport._ListKeyHandles._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = autokey.ListKeyHandlesResponse() - pb_resp = autokey.ListKeyHandlesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_key_handles(resp) - return resp - - @property - def create_key_handle(self) -> Callable[ - [autokey.CreateKeyHandleRequest], - 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._CreateKeyHandle(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_key_handle(self) -> Callable[ - [autokey.GetKeyHandleRequest], - autokey.KeyHandle]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetKeyHandle(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_key_handles(self) -> Callable[ - [autokey.ListKeyHandlesRequest], - autokey.ListKeyHandlesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListKeyHandles(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(_BaseAutokeyRestTransport._BaseGetLocation, AutokeyRestStub): - def __hash__(self): - return hash("AutokeyRestTransport.GetLocation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseAutokeyRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseAutokeyRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.Location() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseAutokeyRestTransport._BaseListLocations, AutokeyRestStub): - def __hash__(self): - return hash("AutokeyRestTransport.ListLocations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseAutokeyRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseAutokeyRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseAutokeyRestTransport._BaseGetIamPolicy, AutokeyRestStub): - def __hash__(self): - return hash("AutokeyRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseAutokeyRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseAutokeyRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseAutokeyRestTransport._BaseSetIamPolicy, AutokeyRestStub): - def __hash__(self): - return hash("AutokeyRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseAutokeyRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseAutokeyRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseAutokeyRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAutokeyRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseAutokeyRestTransport._BaseTestIamPermissions, AutokeyRestStub): - def __hash__(self): - return hash("AutokeyRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseAutokeyRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseAutokeyRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseAutokeyRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAutokeyRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseAutokeyRestTransport._BaseGetOperation, AutokeyRestStub): - def __hash__(self): - return hash("AutokeyRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, 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 = _BaseAutokeyRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseAutokeyRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AutokeyRestTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest_base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest_base.py deleted file mode 100644 index f2801b90062f..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey/transports/rest_base.py +++ /dev/null @@ -1,434 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import AutokeyTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.kms_v1.types import autokey -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseAutokeyRestTransport(AutokeyTransport): - """Base REST backend transport for Autokey. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'cloudkms.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[Any]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseCreateKeyHandle: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/keyHandles', - 'body': 'key_handle', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = autokey.CreateKeyHandleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAutokeyRestTransport._BaseCreateKeyHandle._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetKeyHandle: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/keyHandles/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = autokey.GetKeyHandleRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAutokeyRestTransport._BaseGetKeyHandle._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListKeyHandles: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/keyHandles', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = autokey.ListKeyHandlesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAutokeyRestTransport._BaseListKeyHandles._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetLocation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListLocations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:getIamPolicy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseSetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseTestIamPermissions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseAutokeyRestTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/__init__.py deleted file mode 100644 index da33906ea63a..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import AutokeyAdminClient -from .async_client import AutokeyAdminAsyncClient - -__all__ = ( - 'AutokeyAdminClient', - 'AutokeyAdminAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/async_client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/async_client.py deleted file mode 100644 index 8c98490639ad..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/async_client.py +++ /dev/null @@ -1,1018 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.kms_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.cloud.kms_v1.types import autokey_admin -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import AutokeyAdminTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AutokeyAdminGrpcAsyncIOTransport -from .client import AutokeyAdminClient - - -class AutokeyAdminAsyncClient: - """Provides interfaces for managing `Cloud KMS - Autokey `__ folder-level - configurations. A configuration is inherited by all descendent - projects. A configuration at one folder overrides any other - configurations in its ancestry. Setting a configuration on a folder - is a prerequisite for Cloud KMS Autokey, so that users working in a - descendant project can request provisioned - [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer - Managed Encryption Key (CMEK) use, on-demand. - """ - - _client: AutokeyAdminClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = AutokeyAdminClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AutokeyAdminClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = AutokeyAdminClient._DEFAULT_UNIVERSE - - autokey_config_path = staticmethod(AutokeyAdminClient.autokey_config_path) - parse_autokey_config_path = staticmethod(AutokeyAdminClient.parse_autokey_config_path) - common_billing_account_path = staticmethod(AutokeyAdminClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(AutokeyAdminClient.parse_common_billing_account_path) - common_folder_path = staticmethod(AutokeyAdminClient.common_folder_path) - parse_common_folder_path = staticmethod(AutokeyAdminClient.parse_common_folder_path) - common_organization_path = staticmethod(AutokeyAdminClient.common_organization_path) - parse_common_organization_path = staticmethod(AutokeyAdminClient.parse_common_organization_path) - common_project_path = staticmethod(AutokeyAdminClient.common_project_path) - parse_common_project_path = staticmethod(AutokeyAdminClient.parse_common_project_path) - common_location_path = staticmethod(AutokeyAdminClient.common_location_path) - parse_common_location_path = staticmethod(AutokeyAdminClient.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: - AutokeyAdminAsyncClient: The constructed client. - """ - return AutokeyAdminClient.from_service_account_info.__func__(AutokeyAdminAsyncClient, 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: - AutokeyAdminAsyncClient: The constructed client. - """ - return AutokeyAdminClient.from_service_account_file.__func__(AutokeyAdminAsyncClient, 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 AutokeyAdminClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> AutokeyAdminTransport: - """Returns the transport used by the client instance. - - Returns: - AutokeyAdminTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = AutokeyAdminClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AutokeyAdminTransport, Callable[..., AutokeyAdminTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the autokey admin async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AutokeyAdminTransport,Callable[..., AutokeyAdminTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the AutokeyAdminTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = AutokeyAdminClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def update_autokey_config(self, - request: Optional[Union[autokey_admin.UpdateAutokeyConfigRequest, dict]] = None, - *, - autokey_config: Optional[autokey_admin.AutokeyConfig] = 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]] = (), - ) -> autokey_admin.AutokeyConfig: - r"""Updates the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] - for a folder. The caller must have both - ``cloudkms.autokeyConfigs.update`` permission on the parent - folder and ``cloudkms.cryptoKeys.setIamPolicy`` permission on - the provided key project. A - [KeyHandle][google.cloud.kms.v1.KeyHandle] creation in the - folder's descendant projects will use this configuration to - determine where to create the resulting - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_update_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateAutokeyConfigRequest( - ) - - # Make the request - response = await client.update_autokey_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.UpdateAutokeyConfigRequest, dict]]): - The request object. Request message for - [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig]. - autokey_config (:class:`google.cloud.kms_v1.types.AutokeyConfig`): - Required. - [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] with - values to update. - - This corresponds to the ``autokey_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Masks which fields of the - [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] to - update, e.g. ``keyProject``. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.AutokeyConfig: - Cloud KMS Autokey configuration for a - folder. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([autokey_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey_admin.UpdateAutokeyConfigRequest): - request = autokey_admin.UpdateAutokeyConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if autokey_config is not None: - request.autokey_config = autokey_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_autokey_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("autokey_config.name", request.autokey_config.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_autokey_config(self, - request: Optional[Union[autokey_admin.GetAutokeyConfigRequest, 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]] = (), - ) -> autokey_admin.AutokeyConfig: - r"""Returns the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] - for a folder. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_get_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetAutokeyConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_autokey_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.GetAutokeyConfigRequest, dict]]): - The request object. Request message for - [GetAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig]. - name (:class:`str`): - Required. Name of the - [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] - resource, e.g. - ``folders/{FOLDER_NUMBER}/autokeyConfig``. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.AutokeyConfig: - Cloud KMS Autokey configuration for a - folder. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey_admin.GetAutokeyConfigRequest): - request = autokey_admin.GetAutokeyConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_autokey_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def show_effective_autokey_config(self, - request: Optional[Union[autokey_admin.ShowEffectiveAutokeyConfigRequest, 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]] = (), - ) -> autokey_admin.ShowEffectiveAutokeyConfigResponse: - r"""Returns the effective Cloud KMS Autokey configuration - for a given project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_show_effective_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ShowEffectiveAutokeyConfigRequest( - parent="parent_value", - ) - - # Make the request - response = await client.show_effective_autokey_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.ShowEffectiveAutokeyConfigRequest, dict]]): - The request object. Request message for - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - parent (:class:`str`): - Required. Name of the resource - project to the show effective Cloud KMS - Autokey configuration for. This may be - helpful for interrogating the effect of - nested folder configurations on a given - resource project. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.ShowEffectiveAutokeyConfigResponse: - Response message for - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey_admin.ShowEffectiveAutokeyConfigRequest): - request = autokey_admin.ShowEffectiveAutokeyConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.show_effective_autokey_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_location] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_locations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does - not have a policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified permissions against the IAM access control - policy for a function. - - If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~iam_policy_pb2.PolicyTestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "AutokeyAdminAsyncClient": - 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__ = ( - "AutokeyAdminAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/client.py deleted file mode 100644 index b0a447fce811..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/client.py +++ /dev/null @@ -1,1358 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.kms_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.cloud.kms_v1.types import autokey_admin -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from .transports.base import AutokeyAdminTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AutokeyAdminGrpcTransport -from .transports.grpc_asyncio import AutokeyAdminGrpcAsyncIOTransport -from .transports.rest import AutokeyAdminRestTransport - - -class AutokeyAdminClientMeta(type): - """Metaclass for the AutokeyAdmin 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[AutokeyAdminTransport]] - _transport_registry["grpc"] = AutokeyAdminGrpcTransport - _transport_registry["grpc_asyncio"] = AutokeyAdminGrpcAsyncIOTransport - _transport_registry["rest"] = AutokeyAdminRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[AutokeyAdminTransport]: - """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 AutokeyAdminClient(metaclass=AutokeyAdminClientMeta): - """Provides interfaces for managing `Cloud KMS - Autokey `__ folder-level - configurations. A configuration is inherited by all descendent - projects. A configuration at one folder overrides any other - configurations in its ancestry. Setting a configuration on a folder - is a prerequisite for Cloud KMS Autokey, so that users working in a - descendant project can request provisioned - [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer - Managed Encryption Key (CMEK) use, on-demand. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "cloudkms.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "cloudkms.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - AutokeyAdminClient: 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: - AutokeyAdminClient: 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) -> AutokeyAdminTransport: - """Returns the transport used by the client instance. - - Returns: - AutokeyAdminTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def autokey_config_path(folder: str,) -> str: - """Returns a fully-qualified autokey_config string.""" - return "folders/{folder}/autokeyConfig".format(folder=folder, ) - - @staticmethod - def parse_autokey_config_path(path: str) -> Dict[str,str]: - """Parses a autokey_config path into its component segments.""" - m = re.match(r"^folders/(?P.+?)/autokeyConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = AutokeyAdminClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = AutokeyAdminClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = AutokeyAdminClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, AutokeyAdminTransport, Callable[..., AutokeyAdminTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the autokey admin client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,AutokeyAdminTransport,Callable[..., AutokeyAdminTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the AutokeyAdminTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = AutokeyAdminClient._read_environment_variables() - self._client_cert_source = AutokeyAdminClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = AutokeyAdminClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, AutokeyAdminTransport) - if transport_provided: - # transport is a AutokeyAdminTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(AutokeyAdminTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - AutokeyAdminClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[AutokeyAdminTransport], Callable[..., AutokeyAdminTransport]] = ( - AutokeyAdminClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., AutokeyAdminTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def update_autokey_config(self, - request: Optional[Union[autokey_admin.UpdateAutokeyConfigRequest, dict]] = None, - *, - autokey_config: Optional[autokey_admin.AutokeyConfig] = 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]] = (), - ) -> autokey_admin.AutokeyConfig: - r"""Updates the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] - for a folder. The caller must have both - ``cloudkms.autokeyConfigs.update`` permission on the parent - folder and ``cloudkms.cryptoKeys.setIamPolicy`` permission on - the provided key project. A - [KeyHandle][google.cloud.kms.v1.KeyHandle] creation in the - folder's descendant projects will use this configuration to - determine where to create the resulting - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_update_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminClient() - - # Initialize request argument(s) - request = kms_v1.UpdateAutokeyConfigRequest( - ) - - # Make the request - response = client.update_autokey_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.UpdateAutokeyConfigRequest, dict]): - The request object. Request message for - [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig]. - autokey_config (google.cloud.kms_v1.types.AutokeyConfig): - Required. - [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] with - values to update. - - This corresponds to the ``autokey_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Masks which fields of the - [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] to - update, e.g. ``keyProject``. - - 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.cloud.kms_v1.types.AutokeyConfig: - Cloud KMS Autokey configuration for a - folder. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([autokey_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey_admin.UpdateAutokeyConfigRequest): - request = autokey_admin.UpdateAutokeyConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if autokey_config is not None: - request.autokey_config = autokey_config - 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_autokey_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("autokey_config.name", request.autokey_config.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_autokey_config(self, - request: Optional[Union[autokey_admin.GetAutokeyConfigRequest, 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]] = (), - ) -> autokey_admin.AutokeyConfig: - r"""Returns the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] - for a folder. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_get_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminClient() - - # Initialize request argument(s) - request = kms_v1.GetAutokeyConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_autokey_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.GetAutokeyConfigRequest, dict]): - The request object. Request message for - [GetAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig]. - name (str): - Required. Name of the - [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] - resource, e.g. - ``folders/{FOLDER_NUMBER}/autokeyConfig``. - - 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.kms_v1.types.AutokeyConfig: - Cloud KMS Autokey configuration for a - folder. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey_admin.GetAutokeyConfigRequest): - request = autokey_admin.GetAutokeyConfigRequest(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_autokey_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def show_effective_autokey_config(self, - request: Optional[Union[autokey_admin.ShowEffectiveAutokeyConfigRequest, 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]] = (), - ) -> autokey_admin.ShowEffectiveAutokeyConfigResponse: - r"""Returns the effective Cloud KMS Autokey configuration - for a given project. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_show_effective_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminClient() - - # Initialize request argument(s) - request = kms_v1.ShowEffectiveAutokeyConfigRequest( - parent="parent_value", - ) - - # Make the request - response = client.show_effective_autokey_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.ShowEffectiveAutokeyConfigRequest, dict]): - The request object. Request message for - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - parent (str): - Required. Name of the resource - project to the show effective Cloud KMS - Autokey configuration for. This may be - helpful for interrogating the effect of - nested folder configurations on a given - resource project. - - 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.kms_v1.types.ShowEffectiveAutokeyConfigResponse: - Response message for - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, autokey_admin.ShowEffectiveAutokeyConfigRequest): - request = autokey_admin.ShowEffectiveAutokeyConfigRequest(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.show_effective_autokey_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "AutokeyAdminClient": - 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 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 = self._transport._wrapped_methods[self._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_location] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_locations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "AutokeyAdminClient", -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/README.rst b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/README.rst deleted file mode 100644 index e031a9fac606..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`AutokeyAdminTransport` is the ABC for all transports. -- public child `AutokeyAdminGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `AutokeyAdminGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseAutokeyAdminRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `AutokeyAdminRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/__init__.py deleted file mode 100644 index 16792e9f9d1a..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import AutokeyAdminTransport -from .grpc import AutokeyAdminGrpcTransport -from .grpc_asyncio import AutokeyAdminGrpcAsyncIOTransport -from .rest import AutokeyAdminRestTransport -from .rest import AutokeyAdminRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AutokeyAdminTransport]] -_transport_registry['grpc'] = AutokeyAdminGrpcTransport -_transport_registry['grpc_asyncio'] = AutokeyAdminGrpcAsyncIOTransport -_transport_registry['rest'] = AutokeyAdminRestTransport - -__all__ = ( - 'AutokeyAdminTransport', - 'AutokeyAdminGrpcTransport', - 'AutokeyAdminGrpcAsyncIOTransport', - 'AutokeyAdminRestTransport', - 'AutokeyAdminRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/base.py deleted file mode 100644 index b70e09688a7e..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/base.py +++ /dev/null @@ -1,302 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.kms_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.kms_v1.types import autokey_admin -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class AutokeyAdminTransport(abc.ABC): - """Abstract transport class for AutokeyAdmin.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', - ) - - DEFAULT_HOST: str = 'cloudkms.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.update_autokey_config: gapic_v1.method.wrap_method( - self.update_autokey_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_autokey_config: gapic_v1.method.wrap_method( - self.get_autokey_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.show_effective_autokey_config: gapic_v1.method.wrap_method( - self.show_effective_autokey_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - } - - 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 update_autokey_config(self) -> Callable[ - [autokey_admin.UpdateAutokeyConfigRequest], - Union[ - autokey_admin.AutokeyConfig, - Awaitable[autokey_admin.AutokeyConfig] - ]]: - raise NotImplementedError() - - @property - def get_autokey_config(self) -> Callable[ - [autokey_admin.GetAutokeyConfigRequest], - Union[ - autokey_admin.AutokeyConfig, - Awaitable[autokey_admin.AutokeyConfig] - ]]: - raise NotImplementedError() - - @property - def show_effective_autokey_config(self) -> Callable[ - [autokey_admin.ShowEffectiveAutokeyConfigRequest], - Union[ - autokey_admin.ShowEffectiveAutokeyConfigResponse, - Awaitable[autokey_admin.ShowEffectiveAutokeyConfigResponse] - ]]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'AutokeyAdminTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc.py deleted file mode 100644 index dc3ee2da4098..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc.py +++ /dev/null @@ -1,477 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.kms_v1.types import autokey_admin -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import AutokeyAdminTransport, DEFAULT_CLIENT_INFO - - -class AutokeyAdminGrpcTransport(AutokeyAdminTransport): - """gRPC backend transport for AutokeyAdmin. - - Provides interfaces for managing `Cloud KMS - Autokey `__ folder-level - configurations. A configuration is inherited by all descendent - projects. A configuration at one folder overrides any other - configurations in its ancestry. Setting a configuration on a folder - is a prerequisite for Cloud KMS Autokey, so that users working in a - descendant project can request provisioned - [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer - Managed Encryption Key (CMEK) use, on-demand. - - 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 = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudkms.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 update_autokey_config(self) -> Callable[ - [autokey_admin.UpdateAutokeyConfigRequest], - autokey_admin.AutokeyConfig]: - r"""Return a callable for the update autokey config method over gRPC. - - Updates the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] - for a folder. The caller must have both - ``cloudkms.autokeyConfigs.update`` permission on the parent - folder and ``cloudkms.cryptoKeys.setIamPolicy`` permission on - the provided key project. A - [KeyHandle][google.cloud.kms.v1.KeyHandle] creation in the - folder's descendant projects will use this configuration to - determine where to create the resulting - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.UpdateAutokeyConfigRequest], - ~.AutokeyConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_autokey_config' not in self._stubs: - self._stubs['update_autokey_config'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.AutokeyAdmin/UpdateAutokeyConfig', - request_serializer=autokey_admin.UpdateAutokeyConfigRequest.serialize, - response_deserializer=autokey_admin.AutokeyConfig.deserialize, - ) - return self._stubs['update_autokey_config'] - - @property - def get_autokey_config(self) -> Callable[ - [autokey_admin.GetAutokeyConfigRequest], - autokey_admin.AutokeyConfig]: - r"""Return a callable for the get autokey config method over gRPC. - - Returns the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] - for a folder. - - Returns: - Callable[[~.GetAutokeyConfigRequest], - ~.AutokeyConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_autokey_config' not in self._stubs: - self._stubs['get_autokey_config'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.AutokeyAdmin/GetAutokeyConfig', - request_serializer=autokey_admin.GetAutokeyConfigRequest.serialize, - response_deserializer=autokey_admin.AutokeyConfig.deserialize, - ) - return self._stubs['get_autokey_config'] - - @property - def show_effective_autokey_config(self) -> Callable[ - [autokey_admin.ShowEffectiveAutokeyConfigRequest], - autokey_admin.ShowEffectiveAutokeyConfigResponse]: - r"""Return a callable for the show effective autokey config method over gRPC. - - Returns the effective Cloud KMS Autokey configuration - for a given project. - - Returns: - Callable[[~.ShowEffectiveAutokeyConfigRequest], - ~.ShowEffectiveAutokeyConfigResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'show_effective_autokey_config' not in self._stubs: - self._stubs['show_effective_autokey_config'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.AutokeyAdmin/ShowEffectiveAutokeyConfig', - request_serializer=autokey_admin.ShowEffectiveAutokeyConfigRequest.serialize, - response_deserializer=autokey_admin.ShowEffectiveAutokeyConfigResponse.deserialize, - ) - return self._stubs['show_effective_autokey_config'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - def close(self): - self.grpc_channel.close() - - @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_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'AutokeyAdminGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc_asyncio.py deleted file mode 100644 index 68e7a9fb896d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/grpc_asyncio.py +++ /dev/null @@ -1,569 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.kms_v1.types import autokey_admin -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import AutokeyAdminTransport, DEFAULT_CLIENT_INFO -from .grpc import AutokeyAdminGrpcTransport - - -class AutokeyAdminGrpcAsyncIOTransport(AutokeyAdminTransport): - """gRPC AsyncIO backend transport for AutokeyAdmin. - - Provides interfaces for managing `Cloud KMS - Autokey `__ folder-level - configurations. A configuration is inherited by all descendent - projects. A configuration at one folder overrides any other - configurations in its ancestry. Setting a configuration on a folder - is a prerequisite for Cloud KMS Autokey, so that users working in a - descendant project can request provisioned - [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer - Managed Encryption Key (CMEK) use, on-demand. - - 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 = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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 update_autokey_config(self) -> Callable[ - [autokey_admin.UpdateAutokeyConfigRequest], - Awaitable[autokey_admin.AutokeyConfig]]: - r"""Return a callable for the update autokey config method over gRPC. - - Updates the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] - for a folder. The caller must have both - ``cloudkms.autokeyConfigs.update`` permission on the parent - folder and ``cloudkms.cryptoKeys.setIamPolicy`` permission on - the provided key project. A - [KeyHandle][google.cloud.kms.v1.KeyHandle] creation in the - folder's descendant projects will use this configuration to - determine where to create the resulting - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.UpdateAutokeyConfigRequest], - Awaitable[~.AutokeyConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_autokey_config' not in self._stubs: - self._stubs['update_autokey_config'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.AutokeyAdmin/UpdateAutokeyConfig', - request_serializer=autokey_admin.UpdateAutokeyConfigRequest.serialize, - response_deserializer=autokey_admin.AutokeyConfig.deserialize, - ) - return self._stubs['update_autokey_config'] - - @property - def get_autokey_config(self) -> Callable[ - [autokey_admin.GetAutokeyConfigRequest], - Awaitable[autokey_admin.AutokeyConfig]]: - r"""Return a callable for the get autokey config method over gRPC. - - Returns the [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] - for a folder. - - Returns: - Callable[[~.GetAutokeyConfigRequest], - Awaitable[~.AutokeyConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_autokey_config' not in self._stubs: - self._stubs['get_autokey_config'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.AutokeyAdmin/GetAutokeyConfig', - request_serializer=autokey_admin.GetAutokeyConfigRequest.serialize, - response_deserializer=autokey_admin.AutokeyConfig.deserialize, - ) - return self._stubs['get_autokey_config'] - - @property - def show_effective_autokey_config(self) -> Callable[ - [autokey_admin.ShowEffectiveAutokeyConfigRequest], - Awaitable[autokey_admin.ShowEffectiveAutokeyConfigResponse]]: - r"""Return a callable for the show effective autokey config method over gRPC. - - Returns the effective Cloud KMS Autokey configuration - for a given project. - - Returns: - Callable[[~.ShowEffectiveAutokeyConfigRequest], - Awaitable[~.ShowEffectiveAutokeyConfigResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'show_effective_autokey_config' not in self._stubs: - self._stubs['show_effective_autokey_config'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.AutokeyAdmin/ShowEffectiveAutokeyConfig', - request_serializer=autokey_admin.ShowEffectiveAutokeyConfigRequest.serialize, - response_deserializer=autokey_admin.ShowEffectiveAutokeyConfigResponse.deserialize, - ) - return self._stubs['show_effective_autokey_config'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.update_autokey_config: self._wrap_method( - self.update_autokey_config, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_autokey_config: self._wrap_method( - self.get_autokey_config, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.show_effective_autokey_config: self._wrap_method( - self.show_effective_autokey_config, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @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_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'AutokeyAdminGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest.py deleted file mode 100644 index 49a8d4f9fbe2..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest.py +++ /dev/null @@ -1,1077 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -from google.auth.transport.requests import AuthorizedSession # type: ignore -import json # type: ignore -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.kms_v1.types import autokey_admin -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseAutokeyAdminRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - - -class AutokeyAdminRestInterceptor: - """Interceptor for AutokeyAdmin. - - 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 AutokeyAdminRestTransport. - - .. code-block:: python - class MyCustomAutokeyAdminInterceptor(AutokeyAdminRestInterceptor): - def pre_get_autokey_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_autokey_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_show_effective_autokey_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_show_effective_autokey_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_autokey_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_autokey_config(self, response): - logging.log(f"Received response: {response}") - return response - - transport = AutokeyAdminRestTransport(interceptor=MyCustomAutokeyAdminInterceptor()) - client = AutokeyAdminClient(transport=transport) - - - """ - def pre_get_autokey_config(self, request: autokey_admin.GetAutokeyConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey_admin.GetAutokeyConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_autokey_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutokeyAdmin server. - """ - return request, metadata - - def post_get_autokey_config(self, response: autokey_admin.AutokeyConfig) -> autokey_admin.AutokeyConfig: - """Post-rpc interceptor for get_autokey_config - - Override in a subclass to manipulate the response - after it is returned by the AutokeyAdmin server but before - it is returned to user code. - """ - return response - - def pre_show_effective_autokey_config(self, request: autokey_admin.ShowEffectiveAutokeyConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey_admin.ShowEffectiveAutokeyConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for show_effective_autokey_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutokeyAdmin server. - """ - return request, metadata - - def post_show_effective_autokey_config(self, response: autokey_admin.ShowEffectiveAutokeyConfigResponse) -> autokey_admin.ShowEffectiveAutokeyConfigResponse: - """Post-rpc interceptor for show_effective_autokey_config - - Override in a subclass to manipulate the response - after it is returned by the AutokeyAdmin server but before - it is returned to user code. - """ - return response - - def pre_update_autokey_config(self, request: autokey_admin.UpdateAutokeyConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[autokey_admin.UpdateAutokeyConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_autokey_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutokeyAdmin server. - """ - return request, metadata - - def post_update_autokey_config(self, response: autokey_admin.AutokeyConfig) -> autokey_admin.AutokeyConfig: - """Post-rpc interceptor for update_autokey_config - - Override in a subclass to manipulate the response - after it is returned by the AutokeyAdmin server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutokeyAdmin server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the AutokeyAdmin server but before - it is returned to user code. - """ - return response - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutokeyAdmin server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the AutokeyAdmin server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutokeyAdmin server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the AutokeyAdmin server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutokeyAdmin server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the AutokeyAdmin server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the AutokeyAdmin server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the AutokeyAdmin 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 AutokeyAdmin 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 AutokeyAdmin server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class AutokeyAdminRestStub: - _session: AuthorizedSession - _host: str - _interceptor: AutokeyAdminRestInterceptor - - -class AutokeyAdminRestTransport(_BaseAutokeyAdminRestTransport): - """REST backend synchronous transport for AutokeyAdmin. - - Provides interfaces for managing `Cloud KMS - Autokey `__ folder-level - configurations. A configuration is inherited by all descendent - projects. A configuration at one folder overrides any other - configurations in its ancestry. Setting a configuration on a folder - is a prerequisite for Cloud KMS Autokey, so that users working in a - descendant project can request provisioned - [CryptoKeys][google.cloud.kms.v1.CryptoKey], ready for Customer - Managed Encryption Key (CMEK) use, on-demand. - - 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 = 'cloudkms.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[AutokeyAdminRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or AutokeyAdminRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _GetAutokeyConfig(_BaseAutokeyAdminRestTransport._BaseGetAutokeyConfig, AutokeyAdminRestStub): - def __hash__(self): - return hash("AutokeyAdminRestTransport.GetAutokeyConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: autokey_admin.GetAutokeyConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> autokey_admin.AutokeyConfig: - r"""Call the get autokey config method over HTTP. - - Args: - request (~.autokey_admin.GetAutokeyConfigRequest): - The request object. Request message for - [GetAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.autokey_admin.AutokeyConfig: - Cloud KMS Autokey configuration for a - folder. - - """ - - http_options = _BaseAutokeyAdminRestTransport._BaseGetAutokeyConfig._get_http_options() - request, metadata = self._interceptor.pre_get_autokey_config(request, metadata) - transcoded_request = _BaseAutokeyAdminRestTransport._BaseGetAutokeyConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyAdminRestTransport._BaseGetAutokeyConfig._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyAdminRestTransport._GetAutokeyConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = autokey_admin.AutokeyConfig() - pb_resp = autokey_admin.AutokeyConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_autokey_config(resp) - return resp - - class _ShowEffectiveAutokeyConfig(_BaseAutokeyAdminRestTransport._BaseShowEffectiveAutokeyConfig, AutokeyAdminRestStub): - def __hash__(self): - return hash("AutokeyAdminRestTransport.ShowEffectiveAutokeyConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: autokey_admin.ShowEffectiveAutokeyConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> autokey_admin.ShowEffectiveAutokeyConfigResponse: - r"""Call the show effective autokey - config method over HTTP. - - Args: - request (~.autokey_admin.ShowEffectiveAutokeyConfigRequest): - The request object. Request message for - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.autokey_admin.ShowEffectiveAutokeyConfigResponse: - Response message for - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - - """ - - http_options = _BaseAutokeyAdminRestTransport._BaseShowEffectiveAutokeyConfig._get_http_options() - request, metadata = self._interceptor.pre_show_effective_autokey_config(request, metadata) - transcoded_request = _BaseAutokeyAdminRestTransport._BaseShowEffectiveAutokeyConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyAdminRestTransport._BaseShowEffectiveAutokeyConfig._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyAdminRestTransport._ShowEffectiveAutokeyConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = autokey_admin.ShowEffectiveAutokeyConfigResponse() - pb_resp = autokey_admin.ShowEffectiveAutokeyConfigResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_show_effective_autokey_config(resp) - return resp - - class _UpdateAutokeyConfig(_BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig, AutokeyAdminRestStub): - def __hash__(self): - return hash("AutokeyAdminRestTransport.UpdateAutokeyConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: autokey_admin.UpdateAutokeyConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> autokey_admin.AutokeyConfig: - r"""Call the update autokey config method over HTTP. - - Args: - request (~.autokey_admin.UpdateAutokeyConfigRequest): - The request object. Request message for - [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.autokey_admin.AutokeyConfig: - Cloud KMS Autokey configuration for a - folder. - - """ - - http_options = _BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig._get_http_options() - request, metadata = self._interceptor.pre_update_autokey_config(request, metadata) - transcoded_request = _BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig._get_transcoded_request(http_options, request) - - body = _BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyAdminRestTransport._UpdateAutokeyConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = autokey_admin.AutokeyConfig() - pb_resp = autokey_admin.AutokeyConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_autokey_config(resp) - return resp - - @property - def get_autokey_config(self) -> Callable[ - [autokey_admin.GetAutokeyConfigRequest], - autokey_admin.AutokeyConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetAutokeyConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def show_effective_autokey_config(self) -> Callable[ - [autokey_admin.ShowEffectiveAutokeyConfigRequest], - autokey_admin.ShowEffectiveAutokeyConfigResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ShowEffectiveAutokeyConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_autokey_config(self) -> Callable[ - [autokey_admin.UpdateAutokeyConfigRequest], - autokey_admin.AutokeyConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateAutokeyConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(_BaseAutokeyAdminRestTransport._BaseGetLocation, AutokeyAdminRestStub): - def __hash__(self): - return hash("AutokeyAdminRestTransport.GetLocation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseAutokeyAdminRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseAutokeyAdminRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyAdminRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyAdminRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.Location() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseAutokeyAdminRestTransport._BaseListLocations, AutokeyAdminRestStub): - def __hash__(self): - return hash("AutokeyAdminRestTransport.ListLocations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseAutokeyAdminRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseAutokeyAdminRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyAdminRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyAdminRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseAutokeyAdminRestTransport._BaseGetIamPolicy, AutokeyAdminRestStub): - def __hash__(self): - return hash("AutokeyAdminRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseAutokeyAdminRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseAutokeyAdminRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyAdminRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyAdminRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseAutokeyAdminRestTransport._BaseSetIamPolicy, AutokeyAdminRestStub): - def __hash__(self): - return hash("AutokeyAdminRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseAutokeyAdminRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseAutokeyAdminRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseAutokeyAdminRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAutokeyAdminRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyAdminRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseAutokeyAdminRestTransport._BaseTestIamPermissions, AutokeyAdminRestStub): - def __hash__(self): - return hash("AutokeyAdminRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseAutokeyAdminRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseAutokeyAdminRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseAutokeyAdminRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseAutokeyAdminRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyAdminRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseAutokeyAdminRestTransport._BaseGetOperation, AutokeyAdminRestStub): - def __hash__(self): - return hash("AutokeyAdminRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, 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 = _BaseAutokeyAdminRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseAutokeyAdminRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseAutokeyAdminRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - # Send the request - response = AutokeyAdminRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'AutokeyAdminRestTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest_base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest_base.py deleted file mode 100644 index dfa81a11c0c4..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/autokey_admin/transports/rest_base.py +++ /dev/null @@ -1,434 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import AutokeyAdminTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.kms_v1.types import autokey_admin -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseAutokeyAdminRestTransport(AutokeyAdminTransport): - """Base REST backend transport for AutokeyAdmin. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'cloudkms.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[Any]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseGetAutokeyConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=folders/*/autokeyConfig}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = autokey_admin.GetAutokeyConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAutokeyAdminRestTransport._BaseGetAutokeyConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseShowEffectiveAutokeyConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*}:showEffectiveAutokeyConfig', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = autokey_admin.ShowEffectiveAutokeyConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAutokeyAdminRestTransport._BaseShowEffectiveAutokeyConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateAutokeyConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{autokey_config.name=folders/*/autokeyConfig}', - 'body': 'autokey_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = autokey_admin.UpdateAutokeyConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseAutokeyAdminRestTransport._BaseUpdateAutokeyConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetLocation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListLocations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:getIamPolicy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseSetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseTestIamPermissions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseAutokeyAdminRestTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/__init__.py deleted file mode 100644 index b284cc950ea1..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import EkmServiceClient -from .async_client import EkmServiceAsyncClient - -__all__ = ( - 'EkmServiceClient', - 'EkmServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/async_client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/async_client.py deleted file mode 100644 index 064a8079440d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/async_client.py +++ /dev/null @@ -1,1526 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.kms_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.cloud.kms_v1.services.ekm_service import pagers -from google.cloud.kms_v1.types import ekm_service -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EkmServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import EkmServiceGrpcAsyncIOTransport -from .client import EkmServiceClient - - -class EkmServiceAsyncClient: - """Google Cloud Key Management EKM Service - - Manages external cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [EkmConnection][google.cloud.kms.v1.EkmConnection] - """ - - _client: EkmServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = EkmServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = EkmServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = EkmServiceClient._DEFAULT_UNIVERSE - - ekm_config_path = staticmethod(EkmServiceClient.ekm_config_path) - parse_ekm_config_path = staticmethod(EkmServiceClient.parse_ekm_config_path) - ekm_connection_path = staticmethod(EkmServiceClient.ekm_connection_path) - parse_ekm_connection_path = staticmethod(EkmServiceClient.parse_ekm_connection_path) - service_path = staticmethod(EkmServiceClient.service_path) - parse_service_path = staticmethod(EkmServiceClient.parse_service_path) - common_billing_account_path = staticmethod(EkmServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(EkmServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(EkmServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(EkmServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(EkmServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(EkmServiceClient.parse_common_organization_path) - common_project_path = staticmethod(EkmServiceClient.common_project_path) - parse_common_project_path = staticmethod(EkmServiceClient.parse_common_project_path) - common_location_path = staticmethod(EkmServiceClient.common_location_path) - parse_common_location_path = staticmethod(EkmServiceClient.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: - EkmServiceAsyncClient: The constructed client. - """ - return EkmServiceClient.from_service_account_info.__func__(EkmServiceAsyncClient, 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: - EkmServiceAsyncClient: The constructed client. - """ - return EkmServiceClient.from_service_account_file.__func__(EkmServiceAsyncClient, 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 EkmServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> EkmServiceTransport: - """Returns the transport used by the client instance. - - Returns: - EkmServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = EkmServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EkmServiceTransport, Callable[..., EkmServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the ekm service async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,EkmServiceTransport,Callable[..., EkmServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the EkmServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = EkmServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_ekm_connections(self, - request: Optional[Union[ekm_service.ListEkmConnectionsRequest, 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.ListEkmConnectionsAsyncPager: - r"""Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_list_ekm_connections(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListEkmConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_ekm_connections(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.ListEkmConnectionsRequest, dict]]): - The request object. Request message for - [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. - parent (:class:`str`): - Required. The resource name of the location associated - with the - [EkmConnections][google.cloud.kms.v1.EkmConnection] to - list, in the format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.services.ekm_service.pagers.ListEkmConnectionsAsyncPager: - Response message for - [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.ListEkmConnectionsRequest): - request = ekm_service.ListEkmConnectionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_ekm_connections] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListEkmConnectionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_ekm_connection(self, - request: Optional[Union[ekm_service.GetEkmConnectionRequest, 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]] = (), - ) -> ekm_service.EkmConnection: - r"""Returns metadata for a given - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_get_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetEkmConnectionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_ekm_connection(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.GetEkmConnectionRequest, dict]]): - The request object. Request message for - [EkmService.GetEkmConnection][google.cloud.kms.v1.EkmService.GetEkmConnection]. - name (:class:`str`): - Required. The - [name][google.cloud.kms.v1.EkmConnection.name] of the - [EkmConnection][google.cloud.kms.v1.EkmConnection] to - get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.EkmConnection: - An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an - individual EKM connection. It can be used for - creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] - and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], - as well as performing cryptographic operations using - keys created within the - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.GetEkmConnectionRequest): - request = ekm_service.GetEkmConnectionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_ekm_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_ekm_connection(self, - request: Optional[Union[ekm_service.CreateEkmConnectionRequest, dict]] = None, - *, - parent: Optional[str] = None, - ekm_connection_id: Optional[str] = None, - ekm_connection: Optional[ekm_service.EkmConnection] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> ekm_service.EkmConnection: - r"""Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] - in a given Project and Location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_create_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.CreateEkmConnectionRequest( - parent="parent_value", - ekm_connection_id="ekm_connection_id_value", - ) - - # Make the request - response = await client.create_ekm_connection(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.CreateEkmConnectionRequest, dict]]): - The request object. Request message for - [EkmService.CreateEkmConnection][google.cloud.kms.v1.EkmService.CreateEkmConnection]. - parent (:class:`str`): - Required. The resource name of the location associated - with the - [EkmConnection][google.cloud.kms.v1.EkmConnection], in - the format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ekm_connection_id (:class:`str`): - Required. It must be unique within a location and match - the regular expression ``[a-zA-Z0-9_-]{1,63}``. - - This corresponds to the ``ekm_connection_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ekm_connection (:class:`google.cloud.kms_v1.types.EkmConnection`): - Required. An - [EkmConnection][google.cloud.kms.v1.EkmConnection] with - initial field values. - - This corresponds to the ``ekm_connection`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.EkmConnection: - An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an - individual EKM connection. It can be used for - creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] - and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], - as well as performing cryptographic operations using - keys created within the - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, ekm_connection_id, ekm_connection]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.CreateEkmConnectionRequest): - request = ekm_service.CreateEkmConnectionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if ekm_connection_id is not None: - request.ekm_connection_id = ekm_connection_id - if ekm_connection is not None: - request.ekm_connection = ekm_connection - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_ekm_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_ekm_connection(self, - request: Optional[Union[ekm_service.UpdateEkmConnectionRequest, dict]] = None, - *, - ekm_connection: Optional[ekm_service.EkmConnection] = 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]] = (), - ) -> ekm_service.EkmConnection: - r"""Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s - metadata. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_update_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateEkmConnectionRequest( - ) - - # Make the request - response = await client.update_ekm_connection(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.UpdateEkmConnectionRequest, dict]]): - The request object. Request message for - [EkmService.UpdateEkmConnection][google.cloud.kms.v1.EkmService.UpdateEkmConnection]. - ekm_connection (:class:`google.cloud.kms_v1.types.EkmConnection`): - Required. - [EkmConnection][google.cloud.kms.v1.EkmConnection] with - updated values. - - This corresponds to the ``ekm_connection`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.EkmConnection: - An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an - individual EKM connection. It can be used for - creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] - and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], - as well as performing cryptographic operations using - keys created within the - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([ekm_connection, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.UpdateEkmConnectionRequest): - request = ekm_service.UpdateEkmConnectionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if ekm_connection is not None: - request.ekm_connection = ekm_connection - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_ekm_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("ekm_connection.name", request.ekm_connection.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_ekm_config(self, - request: Optional[Union[ekm_service.GetEkmConfigRequest, 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]] = (), - ) -> ekm_service.EkmConfig: - r"""Returns the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton - resource for a given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_get_ekm_config(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetEkmConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_ekm_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.GetEkmConfigRequest, dict]]): - The request object. Request message for - [EkmService.GetEkmConfig][google.cloud.kms.v1.EkmService.GetEkmConfig]. - name (:class:`str`): - Required. The [name][google.cloud.kms.v1.EkmConfig.name] - of the [EkmConfig][google.cloud.kms.v1.EkmConfig] to - get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.EkmConfig: - An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a singleton resource that - represents configuration parameters that apply to all - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] - in a given project and location. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.GetEkmConfigRequest): - request = ekm_service.GetEkmConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_ekm_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_ekm_config(self, - request: Optional[Union[ekm_service.UpdateEkmConfigRequest, dict]] = None, - *, - ekm_config: Optional[ekm_service.EkmConfig] = 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]] = (), - ) -> ekm_service.EkmConfig: - r"""Updates the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton - resource for a given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_update_ekm_config(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateEkmConfigRequest( - ) - - # Make the request - response = await client.update_ekm_config(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.UpdateEkmConfigRequest, dict]]): - The request object. Request message for - [EkmService.UpdateEkmConfig][google.cloud.kms.v1.EkmService.UpdateEkmConfig]. - ekm_config (:class:`google.cloud.kms_v1.types.EkmConfig`): - Required. [EkmConfig][google.cloud.kms.v1.EkmConfig] - with updated values. - - This corresponds to the ``ekm_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.EkmConfig: - An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a singleton resource that - represents configuration parameters that apply to all - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] - in a given project and location. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([ekm_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.UpdateEkmConfigRequest): - request = ekm_service.UpdateEkmConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if ekm_config is not None: - request.ekm_config = ekm_config - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_ekm_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("ekm_config.name", request.ekm_config.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def verify_connectivity(self, - request: Optional[Union[ekm_service.VerifyConnectivityRequest, 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]] = (), - ) -> ekm_service.VerifyConnectivityResponse: - r"""Verifies that Cloud KMS can successfully connect to the external - key manager specified by an - [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is - an error connecting to the EKM, this method returns a - FAILED_PRECONDITION status containing structured information as - described at - https://cloud.google.com/kms/docs/reference/ekm_errors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_verify_connectivity(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.VerifyConnectivityRequest( - name="name_value", - ) - - # Make the request - response = await client.verify_connectivity(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.VerifyConnectivityRequest, dict]]): - The request object. Request message for - [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. - name (:class:`str`): - Required. The - [name][google.cloud.kms.v1.EkmConnection.name] of the - [EkmConnection][google.cloud.kms.v1.EkmConnection] to - verify. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.VerifyConnectivityResponse: - Response message for - [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.VerifyConnectivityRequest): - request = ekm_service.VerifyConnectivityRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.verify_connectivity] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_location] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_locations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does - not have a policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified permissions against the IAM access control - policy for a function. - - If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~iam_policy_pb2.PolicyTestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "EkmServiceAsyncClient": - 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__ = ( - "EkmServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/client.py deleted file mode 100644 index 7a7821335cd4..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/client.py +++ /dev/null @@ -1,1880 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.kms_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.cloud.kms_v1.services.ekm_service import pagers -from google.cloud.kms_v1.types import ekm_service -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from .transports.base import EkmServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import EkmServiceGrpcTransport -from .transports.grpc_asyncio import EkmServiceGrpcAsyncIOTransport -from .transports.rest import EkmServiceRestTransport - - -class EkmServiceClientMeta(type): - """Metaclass for the EkmService 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[EkmServiceTransport]] - _transport_registry["grpc"] = EkmServiceGrpcTransport - _transport_registry["grpc_asyncio"] = EkmServiceGrpcAsyncIOTransport - _transport_registry["rest"] = EkmServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[EkmServiceTransport]: - """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 EkmServiceClient(metaclass=EkmServiceClientMeta): - """Google Cloud Key Management EKM Service - - Manages external cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [EkmConnection][google.cloud.kms.v1.EkmConnection] - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "cloudkms.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "cloudkms.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - EkmServiceClient: 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: - EkmServiceClient: 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) -> EkmServiceTransport: - """Returns the transport used by the client instance. - - Returns: - EkmServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def ekm_config_path(project: str,location: str,) -> str: - """Returns a fully-qualified ekm_config string.""" - return "projects/{project}/locations/{location}/ekmConfig".format(project=project, location=location, ) - - @staticmethod - def parse_ekm_config_path(path: str) -> Dict[str,str]: - """Parses a ekm_config path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/ekmConfig$", path) - return m.groupdict() if m else {} - - @staticmethod - def ekm_connection_path(project: str,location: str,ekm_connection: str,) -> str: - """Returns a fully-qualified ekm_connection string.""" - return "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format(project=project, location=location, ekm_connection=ekm_connection, ) - - @staticmethod - def parse_ekm_connection_path(path: str) -> Dict[str,str]: - """Parses a ekm_connection path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/ekmConnections/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def service_path(project: str,location: str,namespace: str,service: str,) -> str: - """Returns a fully-qualified service string.""" - return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - - @staticmethod - def parse_service_path(path: str) -> Dict[str,str]: - """Parses a service path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = EkmServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = EkmServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = EkmServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, EkmServiceTransport, Callable[..., EkmServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the ekm service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,EkmServiceTransport,Callable[..., EkmServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the EkmServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = EkmServiceClient._read_environment_variables() - self._client_cert_source = EkmServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = EkmServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, EkmServiceTransport) - if transport_provided: - # transport is a EkmServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(EkmServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - EkmServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[EkmServiceTransport], Callable[..., EkmServiceTransport]] = ( - EkmServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., EkmServiceTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def list_ekm_connections(self, - request: Optional[Union[ekm_service.ListEkmConnectionsRequest, 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.ListEkmConnectionsPager: - r"""Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_list_ekm_connections(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.ListEkmConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_ekm_connections(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.ListEkmConnectionsRequest, dict]): - The request object. Request message for - [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. - parent (str): - Required. The resource name of the location associated - with the - [EkmConnections][google.cloud.kms.v1.EkmConnection] to - list, in the format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.services.ekm_service.pagers.ListEkmConnectionsPager: - Response message for - [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.ListEkmConnectionsRequest): - request = ekm_service.ListEkmConnectionsRequest(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_ekm_connections] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListEkmConnectionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_ekm_connection(self, - request: Optional[Union[ekm_service.GetEkmConnectionRequest, 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]] = (), - ) -> ekm_service.EkmConnection: - r"""Returns metadata for a given - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_get_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetEkmConnectionRequest( - name="name_value", - ) - - # Make the request - response = client.get_ekm_connection(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.GetEkmConnectionRequest, dict]): - The request object. Request message for - [EkmService.GetEkmConnection][google.cloud.kms.v1.EkmService.GetEkmConnection]. - name (str): - Required. The - [name][google.cloud.kms.v1.EkmConnection.name] of the - [EkmConnection][google.cloud.kms.v1.EkmConnection] to - get. - - 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.kms_v1.types.EkmConnection: - An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an - individual EKM connection. It can be used for - creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] - and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], - as well as performing cryptographic operations using - keys created within the - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.GetEkmConnectionRequest): - request = ekm_service.GetEkmConnectionRequest(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_ekm_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_ekm_connection(self, - request: Optional[Union[ekm_service.CreateEkmConnectionRequest, dict]] = None, - *, - parent: Optional[str] = None, - ekm_connection_id: Optional[str] = None, - ekm_connection: Optional[ekm_service.EkmConnection] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> ekm_service.EkmConnection: - r"""Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] - in a given Project and Location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_create_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.CreateEkmConnectionRequest( - parent="parent_value", - ekm_connection_id="ekm_connection_id_value", - ) - - # Make the request - response = client.create_ekm_connection(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.CreateEkmConnectionRequest, dict]): - The request object. Request message for - [EkmService.CreateEkmConnection][google.cloud.kms.v1.EkmService.CreateEkmConnection]. - parent (str): - Required. The resource name of the location associated - with the - [EkmConnection][google.cloud.kms.v1.EkmConnection], in - the format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ekm_connection_id (str): - Required. It must be unique within a location and match - the regular expression ``[a-zA-Z0-9_-]{1,63}``. - - This corresponds to the ``ekm_connection_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ekm_connection (google.cloud.kms_v1.types.EkmConnection): - Required. An - [EkmConnection][google.cloud.kms.v1.EkmConnection] with - initial field values. - - This corresponds to the ``ekm_connection`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.EkmConnection: - An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an - individual EKM connection. It can be used for - creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] - and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], - as well as performing cryptographic operations using - keys created within the - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, ekm_connection_id, ekm_connection]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.CreateEkmConnectionRequest): - request = ekm_service.CreateEkmConnectionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if ekm_connection_id is not None: - request.ekm_connection_id = ekm_connection_id - if ekm_connection is not None: - request.ekm_connection = ekm_connection - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_ekm_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_ekm_connection(self, - request: Optional[Union[ekm_service.UpdateEkmConnectionRequest, dict]] = None, - *, - ekm_connection: Optional[ekm_service.EkmConnection] = 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]] = (), - ) -> ekm_service.EkmConnection: - r"""Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s - metadata. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_update_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.UpdateEkmConnectionRequest( - ) - - # Make the request - response = client.update_ekm_connection(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.UpdateEkmConnectionRequest, dict]): - The request object. Request message for - [EkmService.UpdateEkmConnection][google.cloud.kms.v1.EkmService.UpdateEkmConnection]. - ekm_connection (google.cloud.kms_v1.types.EkmConnection): - Required. - [EkmConnection][google.cloud.kms.v1.EkmConnection] with - updated values. - - This corresponds to the ``ekm_connection`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be - updated in this request. - - 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.cloud.kms_v1.types.EkmConnection: - An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an - individual EKM connection. It can be used for - creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] - and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], - as well as performing cryptographic operations using - keys created within the - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([ekm_connection, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.UpdateEkmConnectionRequest): - request = ekm_service.UpdateEkmConnectionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if ekm_connection is not None: - request.ekm_connection = ekm_connection - 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_ekm_connection] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("ekm_connection.name", request.ekm_connection.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_ekm_config(self, - request: Optional[Union[ekm_service.GetEkmConfigRequest, 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]] = (), - ) -> ekm_service.EkmConfig: - r"""Returns the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton - resource for a given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_get_ekm_config(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetEkmConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_ekm_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.GetEkmConfigRequest, dict]): - The request object. Request message for - [EkmService.GetEkmConfig][google.cloud.kms.v1.EkmService.GetEkmConfig]. - name (str): - Required. The [name][google.cloud.kms.v1.EkmConfig.name] - of the [EkmConfig][google.cloud.kms.v1.EkmConfig] to - get. - - 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.kms_v1.types.EkmConfig: - An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a singleton resource that - represents configuration parameters that apply to all - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] - in a given project and location. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.GetEkmConfigRequest): - request = ekm_service.GetEkmConfigRequest(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_ekm_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_ekm_config(self, - request: Optional[Union[ekm_service.UpdateEkmConfigRequest, dict]] = None, - *, - ekm_config: Optional[ekm_service.EkmConfig] = 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]] = (), - ) -> ekm_service.EkmConfig: - r"""Updates the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton - resource for a given project and location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_update_ekm_config(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.UpdateEkmConfigRequest( - ) - - # Make the request - response = client.update_ekm_config(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.UpdateEkmConfigRequest, dict]): - The request object. Request message for - [EkmService.UpdateEkmConfig][google.cloud.kms.v1.EkmService.UpdateEkmConfig]. - ekm_config (google.cloud.kms_v1.types.EkmConfig): - Required. [EkmConfig][google.cloud.kms.v1.EkmConfig] - with updated values. - - This corresponds to the ``ekm_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be - updated in this request. - - 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.cloud.kms_v1.types.EkmConfig: - An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a singleton resource that - represents configuration parameters that apply to all - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] - in a given project and location. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([ekm_config, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.UpdateEkmConfigRequest): - request = ekm_service.UpdateEkmConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if ekm_config is not None: - request.ekm_config = ekm_config - 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_ekm_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("ekm_config.name", request.ekm_config.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def verify_connectivity(self, - request: Optional[Union[ekm_service.VerifyConnectivityRequest, 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]] = (), - ) -> ekm_service.VerifyConnectivityResponse: - r"""Verifies that Cloud KMS can successfully connect to the external - key manager specified by an - [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is - an error connecting to the EKM, this method returns a - FAILED_PRECONDITION status containing structured information as - described at - https://cloud.google.com/kms/docs/reference/ekm_errors. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_verify_connectivity(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.VerifyConnectivityRequest( - name="name_value", - ) - - # Make the request - response = client.verify_connectivity(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.VerifyConnectivityRequest, dict]): - The request object. Request message for - [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. - name (str): - Required. The - [name][google.cloud.kms.v1.EkmConnection.name] of the - [EkmConnection][google.cloud.kms.v1.EkmConnection] to - verify. - - 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.kms_v1.types.VerifyConnectivityResponse: - Response message for - [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, ekm_service.VerifyConnectivityRequest): - request = ekm_service.VerifyConnectivityRequest(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.verify_connectivity] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "EkmServiceClient": - 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 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 = self._transport._wrapped_methods[self._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_location] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_locations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "EkmServiceClient", -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/pagers.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/pagers.py deleted file mode 100644 index 43533cb1df06..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/pagers.py +++ /dev/null @@ -1,162 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.cloud.kms_v1.types import ekm_service - - -class ListEkmConnectionsPager: - """A pager for iterating through ``list_ekm_connections`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``ekm_connections`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListEkmConnections`` requests and continue to iterate - through the ``ekm_connections`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` - 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[..., ekm_service.ListEkmConnectionsResponse], - request: ekm_service.ListEkmConnectionsRequest, - response: ekm_service.ListEkmConnectionsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListEkmConnectionsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListEkmConnectionsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = ekm_service.ListEkmConnectionsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[ekm_service.ListEkmConnectionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[ekm_service.EkmConnection]: - for page in self.pages: - yield from page.ekm_connections - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListEkmConnectionsAsyncPager: - """A pager for iterating through ``list_ekm_connections`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``ekm_connections`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListEkmConnections`` requests and continue to iterate - through the ``ekm_connections`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListEkmConnectionsResponse` - 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[ekm_service.ListEkmConnectionsResponse]], - request: ekm_service.ListEkmConnectionsRequest, - response: ekm_service.ListEkmConnectionsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListEkmConnectionsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListEkmConnectionsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = ekm_service.ListEkmConnectionsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[ekm_service.ListEkmConnectionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[ekm_service.EkmConnection]: - async def async_generator(): - async for page in self.pages: - for response in page.ekm_connections: - 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-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/README.rst b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/README.rst deleted file mode 100644 index c0fa99e1eca8..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`EkmServiceTransport` is the ABC for all transports. -- public child `EkmServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `EkmServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseEkmServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `EkmServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py deleted file mode 100644 index 65f4d6f3c851..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import EkmServiceTransport -from .grpc import EkmServiceGrpcTransport -from .grpc_asyncio import EkmServiceGrpcAsyncIOTransport -from .rest import EkmServiceRestTransport -from .rest import EkmServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[EkmServiceTransport]] -_transport_registry['grpc'] = EkmServiceGrpcTransport -_transport_registry['grpc_asyncio'] = EkmServiceGrpcAsyncIOTransport -_transport_registry['rest'] = EkmServiceRestTransport - -__all__ = ( - 'EkmServiceTransport', - 'EkmServiceGrpcTransport', - 'EkmServiceGrpcAsyncIOTransport', - 'EkmServiceRestTransport', - 'EkmServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py deleted file mode 100644 index 6b029761cb3f..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/base.py +++ /dev/null @@ -1,368 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.kms_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.kms_v1.types import ekm_service -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class EkmServiceTransport(abc.ABC): - """Abstract transport class for EkmService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', - ) - - DEFAULT_HOST: str = 'cloudkms.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_ekm_connections: gapic_v1.method.wrap_method( - self.list_ekm_connections, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_ekm_connection: gapic_v1.method.wrap_method( - self.get_ekm_connection, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_ekm_connection: gapic_v1.method.wrap_method( - self.create_ekm_connection, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_ekm_connection: gapic_v1.method.wrap_method( - self.update_ekm_connection, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_ekm_config: gapic_v1.method.wrap_method( - self.get_ekm_config, - default_timeout=None, - client_info=client_info, - ), - self.update_ekm_config: gapic_v1.method.wrap_method( - self.update_ekm_config, - default_timeout=None, - client_info=client_info, - ), - self.verify_connectivity: gapic_v1.method.wrap_method( - self.verify_connectivity, - default_timeout=None, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - } - - 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_ekm_connections(self) -> Callable[ - [ekm_service.ListEkmConnectionsRequest], - Union[ - ekm_service.ListEkmConnectionsResponse, - Awaitable[ekm_service.ListEkmConnectionsResponse] - ]]: - raise NotImplementedError() - - @property - def get_ekm_connection(self) -> Callable[ - [ekm_service.GetEkmConnectionRequest], - Union[ - ekm_service.EkmConnection, - Awaitable[ekm_service.EkmConnection] - ]]: - raise NotImplementedError() - - @property - def create_ekm_connection(self) -> Callable[ - [ekm_service.CreateEkmConnectionRequest], - Union[ - ekm_service.EkmConnection, - Awaitable[ekm_service.EkmConnection] - ]]: - raise NotImplementedError() - - @property - def update_ekm_connection(self) -> Callable[ - [ekm_service.UpdateEkmConnectionRequest], - Union[ - ekm_service.EkmConnection, - Awaitable[ekm_service.EkmConnection] - ]]: - raise NotImplementedError() - - @property - def get_ekm_config(self) -> Callable[ - [ekm_service.GetEkmConfigRequest], - Union[ - ekm_service.EkmConfig, - Awaitable[ekm_service.EkmConfig] - ]]: - raise NotImplementedError() - - @property - def update_ekm_config(self) -> Callable[ - [ekm_service.UpdateEkmConfigRequest], - Union[ - ekm_service.EkmConfig, - Awaitable[ekm_service.EkmConfig] - ]]: - raise NotImplementedError() - - @property - def verify_connectivity(self) -> Callable[ - [ekm_service.VerifyConnectivityRequest], - Union[ - ekm_service.VerifyConnectivityResponse, - Awaitable[ekm_service.VerifyConnectivityResponse] - ]]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'EkmServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py deleted file mode 100644 index b41fc92314e1..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc.py +++ /dev/null @@ -1,579 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.kms_v1.types import ekm_service -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import EkmServiceTransport, DEFAULT_CLIENT_INFO - - -class EkmServiceGrpcTransport(EkmServiceTransport): - """gRPC backend transport for EkmService. - - Google Cloud Key Management EKM Service - - Manages external cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [EkmConnection][google.cloud.kms.v1.EkmConnection] - - 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 = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudkms.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_ekm_connections(self) -> Callable[ - [ekm_service.ListEkmConnectionsRequest], - ekm_service.ListEkmConnectionsResponse]: - r"""Return a callable for the list ekm connections method over gRPC. - - Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. - - Returns: - Callable[[~.ListEkmConnectionsRequest], - ~.ListEkmConnectionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_connections' not in self._stubs: - self._stubs['list_ekm_connections'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/ListEkmConnections', - request_serializer=ekm_service.ListEkmConnectionsRequest.serialize, - response_deserializer=ekm_service.ListEkmConnectionsResponse.deserialize, - ) - return self._stubs['list_ekm_connections'] - - @property - def get_ekm_connection(self) -> Callable[ - [ekm_service.GetEkmConnectionRequest], - ekm_service.EkmConnection]: - r"""Return a callable for the get ekm connection method over gRPC. - - Returns metadata for a given - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - Returns: - Callable[[~.GetEkmConnectionRequest], - ~.EkmConnection]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: - self._stubs['get_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/GetEkmConnection', - request_serializer=ekm_service.GetEkmConnectionRequest.serialize, - response_deserializer=ekm_service.EkmConnection.deserialize, - ) - return self._stubs['get_ekm_connection'] - - @property - def create_ekm_connection(self) -> Callable[ - [ekm_service.CreateEkmConnectionRequest], - ekm_service.EkmConnection]: - r"""Return a callable for the create ekm connection method over gRPC. - - Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] - in a given Project and Location. - - Returns: - Callable[[~.CreateEkmConnectionRequest], - ~.EkmConnection]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: - self._stubs['create_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/CreateEkmConnection', - request_serializer=ekm_service.CreateEkmConnectionRequest.serialize, - response_deserializer=ekm_service.EkmConnection.deserialize, - ) - return self._stubs['create_ekm_connection'] - - @property - def update_ekm_connection(self) -> Callable[ - [ekm_service.UpdateEkmConnectionRequest], - ekm_service.EkmConnection]: - r"""Return a callable for the update ekm connection method over gRPC. - - Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s - metadata. - - Returns: - Callable[[~.UpdateEkmConnectionRequest], - ~.EkmConnection]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: - self._stubs['update_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/UpdateEkmConnection', - request_serializer=ekm_service.UpdateEkmConnectionRequest.serialize, - response_deserializer=ekm_service.EkmConnection.deserialize, - ) - return self._stubs['update_ekm_connection'] - - @property - def get_ekm_config(self) -> Callable[ - [ekm_service.GetEkmConfigRequest], - ekm_service.EkmConfig]: - r"""Return a callable for the get ekm config method over gRPC. - - Returns the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton - resource for a given project and location. - - Returns: - Callable[[~.GetEkmConfigRequest], - ~.EkmConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_config' not in self._stubs: - self._stubs['get_ekm_config'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/GetEkmConfig', - request_serializer=ekm_service.GetEkmConfigRequest.serialize, - response_deserializer=ekm_service.EkmConfig.deserialize, - ) - return self._stubs['get_ekm_config'] - - @property - def update_ekm_config(self) -> Callable[ - [ekm_service.UpdateEkmConfigRequest], - ekm_service.EkmConfig]: - r"""Return a callable for the update ekm config method over gRPC. - - Updates the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton - resource for a given project and location. - - Returns: - Callable[[~.UpdateEkmConfigRequest], - ~.EkmConfig]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_config' not in self._stubs: - self._stubs['update_ekm_config'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/UpdateEkmConfig', - request_serializer=ekm_service.UpdateEkmConfigRequest.serialize, - response_deserializer=ekm_service.EkmConfig.deserialize, - ) - return self._stubs['update_ekm_config'] - - @property - def verify_connectivity(self) -> Callable[ - [ekm_service.VerifyConnectivityRequest], - ekm_service.VerifyConnectivityResponse]: - r"""Return a callable for the verify connectivity method over gRPC. - - Verifies that Cloud KMS can successfully connect to the external - key manager specified by an - [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is - an error connecting to the EKM, this method returns a - FAILED_PRECONDITION status containing structured information as - described at - https://cloud.google.com/kms/docs/reference/ekm_errors. - - Returns: - Callable[[~.VerifyConnectivityRequest], - ~.VerifyConnectivityResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'verify_connectivity' not in self._stubs: - self._stubs['verify_connectivity'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/VerifyConnectivity', - request_serializer=ekm_service.VerifyConnectivityRequest.serialize, - response_deserializer=ekm_service.VerifyConnectivityResponse.deserialize, - ) - return self._stubs['verify_connectivity'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - def close(self): - self.grpc_channel.close() - - @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_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'EkmServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py deleted file mode 100644 index c4e5842edf31..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,701 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.kms_v1.types import ekm_service -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import EkmServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import EkmServiceGrpcTransport - - -class EkmServiceGrpcAsyncIOTransport(EkmServiceTransport): - """gRPC AsyncIO backend transport for EkmService. - - Google Cloud Key Management EKM Service - - Manages external cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [EkmConnection][google.cloud.kms.v1.EkmConnection] - - 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 = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_ekm_connections(self) -> Callable[ - [ekm_service.ListEkmConnectionsRequest], - Awaitable[ekm_service.ListEkmConnectionsResponse]]: - r"""Return a callable for the list ekm connections method over gRPC. - - Lists [EkmConnections][google.cloud.kms.v1.EkmConnection]. - - Returns: - Callable[[~.ListEkmConnectionsRequest], - Awaitable[~.ListEkmConnectionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_connections' not in self._stubs: - self._stubs['list_ekm_connections'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/ListEkmConnections', - request_serializer=ekm_service.ListEkmConnectionsRequest.serialize, - response_deserializer=ekm_service.ListEkmConnectionsResponse.deserialize, - ) - return self._stubs['list_ekm_connections'] - - @property - def get_ekm_connection(self) -> Callable[ - [ekm_service.GetEkmConnectionRequest], - Awaitable[ekm_service.EkmConnection]]: - r"""Return a callable for the get ekm connection method over gRPC. - - Returns metadata for a given - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - Returns: - Callable[[~.GetEkmConnectionRequest], - Awaitable[~.EkmConnection]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: - self._stubs['get_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/GetEkmConnection', - request_serializer=ekm_service.GetEkmConnectionRequest.serialize, - response_deserializer=ekm_service.EkmConnection.deserialize, - ) - return self._stubs['get_ekm_connection'] - - @property - def create_ekm_connection(self) -> Callable[ - [ekm_service.CreateEkmConnectionRequest], - Awaitable[ekm_service.EkmConnection]]: - r"""Return a callable for the create ekm connection method over gRPC. - - Creates a new [EkmConnection][google.cloud.kms.v1.EkmConnection] - in a given Project and Location. - - Returns: - Callable[[~.CreateEkmConnectionRequest], - Awaitable[~.EkmConnection]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: - self._stubs['create_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/CreateEkmConnection', - request_serializer=ekm_service.CreateEkmConnectionRequest.serialize, - response_deserializer=ekm_service.EkmConnection.deserialize, - ) - return self._stubs['create_ekm_connection'] - - @property - def update_ekm_connection(self) -> Callable[ - [ekm_service.UpdateEkmConnectionRequest], - Awaitable[ekm_service.EkmConnection]]: - r"""Return a callable for the update ekm connection method over gRPC. - - Updates an [EkmConnection][google.cloud.kms.v1.EkmConnection]'s - metadata. - - Returns: - Callable[[~.UpdateEkmConnectionRequest], - Awaitable[~.EkmConnection]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_connection' not in self._stubs: - self._stubs['update_ekm_connection'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/UpdateEkmConnection', - request_serializer=ekm_service.UpdateEkmConnectionRequest.serialize, - response_deserializer=ekm_service.EkmConnection.deserialize, - ) - return self._stubs['update_ekm_connection'] - - @property - def get_ekm_config(self) -> Callable[ - [ekm_service.GetEkmConfigRequest], - Awaitable[ekm_service.EkmConfig]]: - r"""Return a callable for the get ekm config method over gRPC. - - Returns the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton - resource for a given project and location. - - Returns: - Callable[[~.GetEkmConfigRequest], - Awaitable[~.EkmConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_config' not in self._stubs: - self._stubs['get_ekm_config'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/GetEkmConfig', - request_serializer=ekm_service.GetEkmConfigRequest.serialize, - response_deserializer=ekm_service.EkmConfig.deserialize, - ) - return self._stubs['get_ekm_config'] - - @property - def update_ekm_config(self) -> Callable[ - [ekm_service.UpdateEkmConfigRequest], - Awaitable[ekm_service.EkmConfig]]: - r"""Return a callable for the update ekm config method over gRPC. - - Updates the [EkmConfig][google.cloud.kms.v1.EkmConfig] singleton - resource for a given project and location. - - Returns: - Callable[[~.UpdateEkmConfigRequest], - Awaitable[~.EkmConfig]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_ekm_config' not in self._stubs: - self._stubs['update_ekm_config'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/UpdateEkmConfig', - request_serializer=ekm_service.UpdateEkmConfigRequest.serialize, - response_deserializer=ekm_service.EkmConfig.deserialize, - ) - return self._stubs['update_ekm_config'] - - @property - def verify_connectivity(self) -> Callable[ - [ekm_service.VerifyConnectivityRequest], - Awaitable[ekm_service.VerifyConnectivityResponse]]: - r"""Return a callable for the verify connectivity method over gRPC. - - Verifies that Cloud KMS can successfully connect to the external - key manager specified by an - [EkmConnection][google.cloud.kms.v1.EkmConnection]. If there is - an error connecting to the EKM, this method returns a - FAILED_PRECONDITION status containing structured information as - described at - https://cloud.google.com/kms/docs/reference/ekm_errors. - - Returns: - Callable[[~.VerifyConnectivityRequest], - Awaitable[~.VerifyConnectivityResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'verify_connectivity' not in self._stubs: - self._stubs['verify_connectivity'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.EkmService/VerifyConnectivity', - request_serializer=ekm_service.VerifyConnectivityRequest.serialize, - response_deserializer=ekm_service.VerifyConnectivityResponse.deserialize, - ) - return self._stubs['verify_connectivity'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_ekm_connections: self._wrap_method( - self.list_ekm_connections, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_ekm_connection: self._wrap_method( - self.get_ekm_connection, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_ekm_connection: self._wrap_method( - self.create_ekm_connection, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_ekm_connection: self._wrap_method( - self.update_ekm_connection, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_ekm_config: self._wrap_method( - self.get_ekm_config, - default_timeout=None, - client_info=client_info, - ), - self.update_ekm_config: self._wrap_method( - self.update_ekm_config, - default_timeout=None, - client_info=client_info, - ), - self.verify_connectivity: self._wrap_method( - self.verify_connectivity, - default_timeout=None, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @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_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'EkmServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest.py deleted file mode 100644 index e25b8b0b7b0f..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest.py +++ /dev/null @@ -1,1553 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.kms_v1.types import ekm_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseEkmServiceRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - - -class EkmServiceRestInterceptor: - """Interceptor for EkmService. - - 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 EkmServiceRestTransport. - - .. code-block:: python - class MyCustomEkmServiceInterceptor(EkmServiceRestInterceptor): - def pre_create_ekm_connection(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_ekm_connection(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_ekm_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_ekm_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_ekm_connection(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_ekm_connection(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_ekm_connections(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_ekm_connections(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_ekm_config(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_ekm_config(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_ekm_connection(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_ekm_connection(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_verify_connectivity(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_verify_connectivity(self, response): - logging.log(f"Received response: {response}") - return response - - transport = EkmServiceRestTransport(interceptor=MyCustomEkmServiceInterceptor()) - client = EkmServiceClient(transport=transport) - - - """ - def pre_create_ekm_connection(self, request: ekm_service.CreateEkmConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.CreateEkmConnectionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_ekm_connection - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_create_ekm_connection(self, response: ekm_service.EkmConnection) -> ekm_service.EkmConnection: - """Post-rpc interceptor for create_ekm_connection - - Override in a subclass to manipulate the response - after it is returned by the EkmService server but before - it is returned to user code. - """ - return response - - def pre_get_ekm_config(self, request: ekm_service.GetEkmConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.GetEkmConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_ekm_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_get_ekm_config(self, response: ekm_service.EkmConfig) -> ekm_service.EkmConfig: - """Post-rpc interceptor for get_ekm_config - - Override in a subclass to manipulate the response - after it is returned by the EkmService server but before - it is returned to user code. - """ - return response - - def pre_get_ekm_connection(self, request: ekm_service.GetEkmConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.GetEkmConnectionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_ekm_connection - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_get_ekm_connection(self, response: ekm_service.EkmConnection) -> ekm_service.EkmConnection: - """Post-rpc interceptor for get_ekm_connection - - Override in a subclass to manipulate the response - after it is returned by the EkmService server but before - it is returned to user code. - """ - return response - - def pre_list_ekm_connections(self, request: ekm_service.ListEkmConnectionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.ListEkmConnectionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_ekm_connections - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_list_ekm_connections(self, response: ekm_service.ListEkmConnectionsResponse) -> ekm_service.ListEkmConnectionsResponse: - """Post-rpc interceptor for list_ekm_connections - - Override in a subclass to manipulate the response - after it is returned by the EkmService server but before - it is returned to user code. - """ - return response - - def pre_update_ekm_config(self, request: ekm_service.UpdateEkmConfigRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.UpdateEkmConfigRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_ekm_config - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_update_ekm_config(self, response: ekm_service.EkmConfig) -> ekm_service.EkmConfig: - """Post-rpc interceptor for update_ekm_config - - Override in a subclass to manipulate the response - after it is returned by the EkmService server but before - it is returned to user code. - """ - return response - - def pre_update_ekm_connection(self, request: ekm_service.UpdateEkmConnectionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.UpdateEkmConnectionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_ekm_connection - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_update_ekm_connection(self, response: ekm_service.EkmConnection) -> ekm_service.EkmConnection: - """Post-rpc interceptor for update_ekm_connection - - Override in a subclass to manipulate the response - after it is returned by the EkmService server but before - it is returned to user code. - """ - return response - - def pre_verify_connectivity(self, request: ekm_service.VerifyConnectivityRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[ekm_service.VerifyConnectivityRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for verify_connectivity - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_verify_connectivity(self, response: ekm_service.VerifyConnectivityResponse) -> ekm_service.VerifyConnectivityResponse: - """Post-rpc interceptor for verify_connectivity - - Override in a subclass to manipulate the response - after it is returned by the EkmService server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the EkmService server but before - it is returned to user code. - """ - return response - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the EkmService server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the EkmService server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the EkmService server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the EkmService server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the EkmService 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 EkmService 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 EkmService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class EkmServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: EkmServiceRestInterceptor - - -class EkmServiceRestTransport(_BaseEkmServiceRestTransport): - """REST backend synchronous transport for EkmService. - - Google Cloud Key Management EKM Service - - Manages external cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [EkmConnection][google.cloud.kms.v1.EkmConnection] - - 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 = 'cloudkms.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[EkmServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or EkmServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _CreateEkmConnection(_BaseEkmServiceRestTransport._BaseCreateEkmConnection, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.CreateEkmConnection") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: ekm_service.CreateEkmConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> ekm_service.EkmConnection: - r"""Call the create ekm connection method over HTTP. - - Args: - request (~.ekm_service.CreateEkmConnectionRequest): - The request object. Request message for - [EkmService.CreateEkmConnection][google.cloud.kms.v1.EkmService.CreateEkmConnection]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.ekm_service.EkmConnection: - An [EkmConnection][google.cloud.kms.v1.EkmConnection] - represents an individual EKM connection. It can be used - for creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] - and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], - as well as performing cryptographic operations using - keys created within the - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - """ - - http_options = _BaseEkmServiceRestTransport._BaseCreateEkmConnection._get_http_options() - request, metadata = self._interceptor.pre_create_ekm_connection(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseCreateEkmConnection._get_transcoded_request(http_options, request) - - body = _BaseEkmServiceRestTransport._BaseCreateEkmConnection._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseCreateEkmConnection._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._CreateEkmConnection._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = ekm_service.EkmConnection() - pb_resp = ekm_service.EkmConnection.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_ekm_connection(resp) - return resp - - class _GetEkmConfig(_BaseEkmServiceRestTransport._BaseGetEkmConfig, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.GetEkmConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: ekm_service.GetEkmConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> ekm_service.EkmConfig: - r"""Call the get ekm config method over HTTP. - - Args: - request (~.ekm_service.GetEkmConfigRequest): - The request object. Request message for - [EkmService.GetEkmConfig][google.cloud.kms.v1.EkmService.GetEkmConfig]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.ekm_service.EkmConfig: - An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a - singleton resource that represents configuration - parameters that apply to all - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] - in a given project and location. - - """ - - http_options = _BaseEkmServiceRestTransport._BaseGetEkmConfig._get_http_options() - request, metadata = self._interceptor.pre_get_ekm_config(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseGetEkmConfig._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseGetEkmConfig._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._GetEkmConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = ekm_service.EkmConfig() - pb_resp = ekm_service.EkmConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_ekm_config(resp) - return resp - - class _GetEkmConnection(_BaseEkmServiceRestTransport._BaseGetEkmConnection, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.GetEkmConnection") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: ekm_service.GetEkmConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> ekm_service.EkmConnection: - r"""Call the get ekm connection method over HTTP. - - Args: - request (~.ekm_service.GetEkmConnectionRequest): - The request object. Request message for - [EkmService.GetEkmConnection][google.cloud.kms.v1.EkmService.GetEkmConnection]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.ekm_service.EkmConnection: - An [EkmConnection][google.cloud.kms.v1.EkmConnection] - represents an individual EKM connection. It can be used - for creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] - and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], - as well as performing cryptographic operations using - keys created within the - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - """ - - http_options = _BaseEkmServiceRestTransport._BaseGetEkmConnection._get_http_options() - request, metadata = self._interceptor.pre_get_ekm_connection(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseGetEkmConnection._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseGetEkmConnection._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._GetEkmConnection._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = ekm_service.EkmConnection() - pb_resp = ekm_service.EkmConnection.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_ekm_connection(resp) - return resp - - class _ListEkmConnections(_BaseEkmServiceRestTransport._BaseListEkmConnections, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.ListEkmConnections") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: ekm_service.ListEkmConnectionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> ekm_service.ListEkmConnectionsResponse: - r"""Call the list ekm connections method over HTTP. - - Args: - request (~.ekm_service.ListEkmConnectionsRequest): - The request object. Request message for - [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.ekm_service.ListEkmConnectionsResponse: - Response message for - [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. - - """ - - http_options = _BaseEkmServiceRestTransport._BaseListEkmConnections._get_http_options() - request, metadata = self._interceptor.pre_list_ekm_connections(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseListEkmConnections._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseListEkmConnections._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._ListEkmConnections._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = ekm_service.ListEkmConnectionsResponse() - pb_resp = ekm_service.ListEkmConnectionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_ekm_connections(resp) - return resp - - class _UpdateEkmConfig(_BaseEkmServiceRestTransport._BaseUpdateEkmConfig, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.UpdateEkmConfig") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: ekm_service.UpdateEkmConfigRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> ekm_service.EkmConfig: - r"""Call the update ekm config method over HTTP. - - Args: - request (~.ekm_service.UpdateEkmConfigRequest): - The request object. Request message for - [EkmService.UpdateEkmConfig][google.cloud.kms.v1.EkmService.UpdateEkmConfig]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.ekm_service.EkmConfig: - An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a - singleton resource that represents configuration - parameters that apply to all - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] - in a given project and location. - - """ - - http_options = _BaseEkmServiceRestTransport._BaseUpdateEkmConfig._get_http_options() - request, metadata = self._interceptor.pre_update_ekm_config(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseUpdateEkmConfig._get_transcoded_request(http_options, request) - - body = _BaseEkmServiceRestTransport._BaseUpdateEkmConfig._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseUpdateEkmConfig._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._UpdateEkmConfig._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = ekm_service.EkmConfig() - pb_resp = ekm_service.EkmConfig.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_ekm_config(resp) - return resp - - class _UpdateEkmConnection(_BaseEkmServiceRestTransport._BaseUpdateEkmConnection, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.UpdateEkmConnection") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: ekm_service.UpdateEkmConnectionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> ekm_service.EkmConnection: - r"""Call the update ekm connection method over HTTP. - - Args: - request (~.ekm_service.UpdateEkmConnectionRequest): - The request object. Request message for - [EkmService.UpdateEkmConnection][google.cloud.kms.v1.EkmService.UpdateEkmConnection]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.ekm_service.EkmConnection: - An [EkmConnection][google.cloud.kms.v1.EkmConnection] - represents an individual EKM connection. It can be used - for creating [CryptoKeys][google.cloud.kms.v1.CryptoKey] - and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], - as well as performing cryptographic operations using - keys created within the - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - """ - - http_options = _BaseEkmServiceRestTransport._BaseUpdateEkmConnection._get_http_options() - request, metadata = self._interceptor.pre_update_ekm_connection(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseUpdateEkmConnection._get_transcoded_request(http_options, request) - - body = _BaseEkmServiceRestTransport._BaseUpdateEkmConnection._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseUpdateEkmConnection._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._UpdateEkmConnection._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = ekm_service.EkmConnection() - pb_resp = ekm_service.EkmConnection.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_ekm_connection(resp) - return resp - - class _VerifyConnectivity(_BaseEkmServiceRestTransport._BaseVerifyConnectivity, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.VerifyConnectivity") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: ekm_service.VerifyConnectivityRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> ekm_service.VerifyConnectivityResponse: - r"""Call the verify connectivity method over HTTP. - - Args: - request (~.ekm_service.VerifyConnectivityRequest): - The request object. Request message for - [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.ekm_service.VerifyConnectivityResponse: - Response message for - [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. - - """ - - http_options = _BaseEkmServiceRestTransport._BaseVerifyConnectivity._get_http_options() - request, metadata = self._interceptor.pre_verify_connectivity(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseVerifyConnectivity._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseVerifyConnectivity._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._VerifyConnectivity._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = ekm_service.VerifyConnectivityResponse() - pb_resp = ekm_service.VerifyConnectivityResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_verify_connectivity(resp) - return resp - - @property - def create_ekm_connection(self) -> Callable[ - [ekm_service.CreateEkmConnectionRequest], - ekm_service.EkmConnection]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateEkmConnection(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_ekm_config(self) -> Callable[ - [ekm_service.GetEkmConfigRequest], - ekm_service.EkmConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEkmConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_ekm_connection(self) -> Callable[ - [ekm_service.GetEkmConnectionRequest], - ekm_service.EkmConnection]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetEkmConnection(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_ekm_connections(self) -> Callable[ - [ekm_service.ListEkmConnectionsRequest], - ekm_service.ListEkmConnectionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListEkmConnections(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_ekm_config(self) -> Callable[ - [ekm_service.UpdateEkmConfigRequest], - ekm_service.EkmConfig]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateEkmConfig(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_ekm_connection(self) -> Callable[ - [ekm_service.UpdateEkmConnectionRequest], - ekm_service.EkmConnection]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateEkmConnection(self._session, self._host, self._interceptor) # type: ignore - - @property - def verify_connectivity(self) -> Callable[ - [ekm_service.VerifyConnectivityRequest], - ekm_service.VerifyConnectivityResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._VerifyConnectivity(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(_BaseEkmServiceRestTransport._BaseGetLocation, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.GetLocation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseEkmServiceRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.Location() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseEkmServiceRestTransport._BaseListLocations, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.ListLocations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseEkmServiceRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseEkmServiceRestTransport._BaseGetIamPolicy, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseEkmServiceRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseEkmServiceRestTransport._BaseSetIamPolicy, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseEkmServiceRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseEkmServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseEkmServiceRestTransport._BaseTestIamPermissions, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseEkmServiceRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseEkmServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseEkmServiceRestTransport._BaseGetOperation, EkmServiceRestStub): - def __hash__(self): - return hash("EkmServiceRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, 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 = _BaseEkmServiceRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseEkmServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseEkmServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - # Send the request - response = EkmServiceRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'EkmServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest_base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest_base.py deleted file mode 100644 index 440865818489..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/ekm_service/transports/rest_base.py +++ /dev/null @@ -1,602 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import EkmServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.kms_v1.types import ekm_service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseEkmServiceRestTransport(EkmServiceTransport): - """Base REST backend transport for EkmService. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'cloudkms.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[Any]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseCreateEkmConnection: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "ekmConnectionId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/ekmConnections', - 'body': 'ekm_connection', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = ekm_service.CreateEkmConnectionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseEkmServiceRestTransport._BaseCreateEkmConnection._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetEkmConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/ekmConfig}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = ekm_service.GetEkmConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseEkmServiceRestTransport._BaseGetEkmConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetEkmConnection: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/ekmConnections/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = ekm_service.GetEkmConnectionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseEkmServiceRestTransport._BaseGetEkmConnection._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListEkmConnections: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/ekmConnections', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = ekm_service.ListEkmConnectionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseEkmServiceRestTransport._BaseListEkmConnections._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateEkmConfig: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{ekm_config.name=projects/*/locations/*/ekmConfig}', - 'body': 'ekm_config', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = ekm_service.UpdateEkmConfigRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseEkmServiceRestTransport._BaseUpdateEkmConfig._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateEkmConnection: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{ekm_connection.name=projects/*/locations/*/ekmConnections/*}', - 'body': 'ekm_connection', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = ekm_service.UpdateEkmConnectionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseEkmServiceRestTransport._BaseUpdateEkmConnection._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseVerifyConnectivity: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/ekmConnections/*}:verifyConnectivity', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = ekm_service.VerifyConnectivityRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseEkmServiceRestTransport._BaseVerifyConnectivity._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetLocation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListLocations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:getIamPolicy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseSetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseTestIamPermissions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseEkmServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/__init__.py deleted file mode 100644 index eec23330da9a..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/__init__.py +++ /dev/null @@ -1,22 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .client import KeyManagementServiceClient -from .async_client import KeyManagementServiceAsyncClient - -__all__ = ( - 'KeyManagementServiceClient', - 'KeyManagementServiceAsyncClient', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/async_client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/async_client.py deleted file mode 100644 index 519f45012e63..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/async_client.py +++ /dev/null @@ -1,4163 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union - -from google.cloud.kms_v1 import gapic_version as package_version - -from google.api_core.client_options import ClientOptions -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.oauth2 import service_account # type: ignore - - -try: - OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore - -from google.cloud.kms_v1.services.key_management_service import pagers -from google.cloud.kms_v1.types import resources -from google.cloud.kms_v1.types import service -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport -from .client import KeyManagementServiceClient - - -class KeyManagementServiceAsyncClient: - """Google Cloud Key Management Service - - Manages cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [KeyRing][google.cloud.kms.v1.KeyRing] - - [CryptoKey][google.cloud.kms.v1.CryptoKey] - - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - - [ImportJob][google.cloud.kms.v1.ImportJob] - - If you are using manual gRPC libraries, see `Using gRPC with Cloud - KMS `__. - """ - - _client: KeyManagementServiceClient - - # Copy defaults from the synchronous client for use here. - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = KeyManagementServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT - _DEFAULT_ENDPOINT_TEMPLATE = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE - _DEFAULT_UNIVERSE = KeyManagementServiceClient._DEFAULT_UNIVERSE - - crypto_key_path = staticmethod(KeyManagementServiceClient.crypto_key_path) - parse_crypto_key_path = staticmethod(KeyManagementServiceClient.parse_crypto_key_path) - crypto_key_version_path = staticmethod(KeyManagementServiceClient.crypto_key_version_path) - parse_crypto_key_version_path = staticmethod(KeyManagementServiceClient.parse_crypto_key_version_path) - import_job_path = staticmethod(KeyManagementServiceClient.import_job_path) - parse_import_job_path = staticmethod(KeyManagementServiceClient.parse_import_job_path) - key_ring_path = staticmethod(KeyManagementServiceClient.key_ring_path) - parse_key_ring_path = staticmethod(KeyManagementServiceClient.parse_key_ring_path) - public_key_path = staticmethod(KeyManagementServiceClient.public_key_path) - parse_public_key_path = staticmethod(KeyManagementServiceClient.parse_public_key_path) - common_billing_account_path = staticmethod(KeyManagementServiceClient.common_billing_account_path) - parse_common_billing_account_path = staticmethod(KeyManagementServiceClient.parse_common_billing_account_path) - common_folder_path = staticmethod(KeyManagementServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(KeyManagementServiceClient.parse_common_folder_path) - common_organization_path = staticmethod(KeyManagementServiceClient.common_organization_path) - parse_common_organization_path = staticmethod(KeyManagementServiceClient.parse_common_organization_path) - common_project_path = staticmethod(KeyManagementServiceClient.common_project_path) - parse_common_project_path = staticmethod(KeyManagementServiceClient.parse_common_project_path) - common_location_path = staticmethod(KeyManagementServiceClient.common_location_path) - parse_common_location_path = staticmethod(KeyManagementServiceClient.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: - KeyManagementServiceAsyncClient: The constructed client. - """ - return KeyManagementServiceClient.from_service_account_info.__func__(KeyManagementServiceAsyncClient, 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: - KeyManagementServiceAsyncClient: The constructed client. - """ - return KeyManagementServiceClient.from_service_account_file.__func__(KeyManagementServiceAsyncClient, 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 KeyManagementServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore - - @property - def transport(self) -> KeyManagementServiceTransport: - """Returns the transport used by the client instance. - - Returns: - KeyManagementServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._client._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used - by the client instance. - """ - return self._client._universe_domain - - get_transport_class = KeyManagementServiceClient.get_transport_class - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, KeyManagementServiceTransport, Callable[..., KeyManagementServiceTransport]]] = "grpc_asyncio", - client_options: Optional[ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the key management service async client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,KeyManagementServiceTransport,Callable[..., KeyManagementServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport to use. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the KeyManagementServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client = KeyManagementServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - - ) - - async def list_key_rings(self, - request: Optional[Union[service.ListKeyRingsRequest, 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.ListKeyRingsAsyncPager: - r"""Lists [KeyRings][google.cloud.kms.v1.KeyRing]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_list_key_rings(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListKeyRingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_key_rings(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.ListKeyRingsRequest, dict]]): - The request object. Request message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - parent (:class:`str`): - Required. The resource name of the location associated - with the [KeyRings][google.cloud.kms.v1.KeyRing], in the - format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.services.key_management_service.pagers.ListKeyRingsAsyncPager: - Response message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListKeyRingsRequest): - request = service.ListKeyRingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_key_rings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListKeyRingsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_crypto_keys(self, - request: Optional[Union[service.ListCryptoKeysRequest, 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.ListCryptoKeysAsyncPager: - r"""Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_list_crypto_keys(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListCryptoKeysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crypto_keys(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.ListCryptoKeysRequest, dict]]): - The request object. Request message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - parent (:class:`str`): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeysAsyncPager: - Response message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListCryptoKeysRequest): - request = service.ListCryptoKeysRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_crypto_keys] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCryptoKeysAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_crypto_key_versions(self, - request: Optional[Union[service.ListCryptoKeyVersionsRequest, 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.ListCryptoKeyVersionsAsyncPager: - r"""Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_list_crypto_key_versions(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListCryptoKeyVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crypto_key_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest, dict]]): - The request object. Request message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - parent (:class:`str`): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in - the format - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsAsyncPager: - Response message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListCryptoKeyVersionsRequest): - request = service.ListCryptoKeyVersionsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_crypto_key_versions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListCryptoKeyVersionsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_import_jobs(self, - request: Optional[Union[service.ListImportJobsRequest, 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.ListImportJobsAsyncPager: - r"""Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_list_import_jobs(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListImportJobsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_import_jobs(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.ListImportJobsRequest, dict]]): - The request object. Request message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - parent (:class:`str`): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.services.key_management_service.pagers.ListImportJobsAsyncPager: - Response message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListImportJobsRequest): - request = service.ListImportJobsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.list_import_jobs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListImportJobsAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_key_ring(self, - request: Optional[Union[service.GetKeyRingRequest, 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]] = (), - ) -> resources.KeyRing: - r"""Returns metadata for a given - [KeyRing][google.cloud.kms.v1.KeyRing]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_get_key_ring(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetKeyRingRequest( - name="name_value", - ) - - # Make the request - response = await client.get_key_ring(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.GetKeyRingRequest, dict]]): - The request object. Request message for - [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. - name (:class:`str`): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the [KeyRing][google.cloud.kms.v1.KeyRing] to get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetKeyRingRequest): - request = service.GetKeyRingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_key_ring] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_crypto_key(self, - request: Optional[Union[service.GetCryptoKeyRequest, 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]] = (), - ) -> resources.CryptoKey: - r"""Returns metadata for a given - [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its - [primary][google.cloud.kms.v1.CryptoKey.primary] - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_get_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetCryptoKeyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_crypto_key(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.GetCryptoKeyRequest, dict]]): - The request object. Request message for - [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. - name (:class:`str`): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] - of the [CryptoKey][google.cloud.kms.v1.CryptoKey] to - get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that - can be used for cryptographic operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetCryptoKeyRequest): - request = service.GetCryptoKeyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_crypto_key] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_crypto_key_version(self, - request: Optional[Union[service.GetCryptoKeyVersionRequest, 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]] = (), - ) -> resources.CryptoKeyVersion: - r"""Returns metadata for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_get_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.GetCryptoKeyVersionRequest, dict]]): - The request object. Request message for - [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. - name (:class:`str`): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetCryptoKeyVersionRequest): - request = service.GetCryptoKeyVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_public_key(self, - request: Optional[Union[service.GetPublicKeyRequest, 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]] = (), - ) -> resources.PublicKey: - r"""Returns the public key for the given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] - or - [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_get_public_key(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetPublicKeyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_public_key(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.GetPublicKeyRequest, dict]]): - The request object. Request message for - [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - name (:class:`str`): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - public key to get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.PublicKey: - The public keys for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - Obtained via - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetPublicKeyRequest): - request = service.GetPublicKeyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_public_key] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_import_job(self, - request: Optional[Union[service.GetImportJobRequest, 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]] = (), - ) -> resources.ImportJob: - r"""Returns metadata for a given - [ImportJob][google.cloud.kms.v1.ImportJob]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_get_import_job(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetImportJobRequest( - name="name_value", - ) - - # Make the request - response = await client.get_import_job(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.GetImportJobRequest, dict]]): - The request object. Request message for - [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. - name (:class:`str`): - Required. The [name][google.cloud.kms.v1.ImportJob.name] - of the [ImportJob][google.cloud.kms.v1.ImportJob] to - get. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - using pre-existing key material, generated outside of - Cloud KMS. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", - which is a public/private key pair. You use the - wrapping key to encrypt (also known as wrap) the - pre-existing key material to protect it during the - import process. The nature of the wrapping key - depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be - set to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be - used to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires - 3 days after it is created. Once expired, Cloud KMS - will no longer be able to import or unwrap any key - material that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public - key. - - For more information, see [Importing a - key](\ https://cloud.google.com/kms/docs/importing-a-key). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetImportJobRequest): - request = service.GetImportJobRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.get_import_job] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_key_ring(self, - request: Optional[Union[service.CreateKeyRingRequest, dict]] = None, - *, - parent: Optional[str] = None, - key_ring_id: Optional[str] = None, - key_ring: Optional[resources.KeyRing] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.KeyRing: - r"""Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given - Project and Location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_create_key_ring(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.CreateKeyRingRequest( - parent="parent_value", - key_ring_id="key_ring_id_value", - ) - - # Make the request - response = await client.create_key_ring(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.CreateKeyRingRequest, dict]]): - The request object. Request message for - [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. - parent (:class:`str`): - Required. The resource name of the location associated - with the [KeyRings][google.cloud.kms.v1.KeyRing], in the - format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_ring_id (:class:`str`): - Required. It must be unique within a location and match - the regular expression ``[a-zA-Z0-9_-]{1,63}`` - - This corresponds to the ``key_ring_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_ring (:class:`google.cloud.kms_v1.types.KeyRing`): - Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with - initial field values. - - This corresponds to the ``key_ring`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, key_ring_id, key_ring]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.CreateKeyRingRequest): - request = service.CreateKeyRingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if key_ring_id is not None: - request.key_ring_id = key_ring_id - if key_ring is not None: - request.key_ring = key_ring - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_key_ring] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_crypto_key(self, - request: Optional[Union[service.CreateCryptoKeyRequest, dict]] = None, - *, - parent: Optional[str] = None, - crypto_key_id: Optional[str] = None, - crypto_key: Optional[resources.CryptoKey] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and - [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] - are required. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_create_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.CreateCryptoKeyRequest( - parent="parent_value", - crypto_key_id="crypto_key_id_value", - ) - - # Make the request - response = await client.create_crypto_key(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.CreateCryptoKeyRequest, dict]]): - The request object. Request message for - [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. - parent (:class:`str`): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the KeyRing associated with the - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_id (:class:`str`): - Required. It must be unique within a KeyRing and match - the regular expression ``[a-zA-Z0-9_-]{1,63}`` - - This corresponds to the ``crypto_key_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key (:class:`google.cloud.kms_v1.types.CryptoKey`): - Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] - with initial field values. - - This corresponds to the ``crypto_key`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that - can be used for cryptographic operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, crypto_key_id, crypto_key]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.CreateCryptoKeyRequest): - request = service.CreateCryptoKeyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if crypto_key_id is not None: - request.crypto_key_id = crypto_key_id - if crypto_key is not None: - request.crypto_key = crypto_key - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_crypto_key] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_crypto_key_version(self, - request: Optional[Union[service.CreateCryptoKeyVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - crypto_key_version: Optional[resources.CryptoKeyVersion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Create a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - The server will assign the next sequential id. If unset, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_create_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.CreateCryptoKeyVersionRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest, dict]]): - The request object. Request message for - [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. - parent (:class:`str`): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] - of the [CryptoKey][google.cloud.kms.v1.CryptoKey] - associated with the - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_version (:class:`google.cloud.kms_v1.types.CryptoKeyVersion`): - Required. A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with initial field values. - - This corresponds to the ``crypto_key_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, crypto_key_version]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.CreateCryptoKeyVersionRequest): - request = service.CreateCryptoKeyVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if crypto_key_version is not None: - request.crypto_key_version = crypto_key_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def import_crypto_key_version(self, - request: Optional[Union[service.ImportCryptoKeyVersionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Import wrapped key material into a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - All requests must specify a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is - additionally specified in the request, key material will be - reimported into that version. Otherwise, a new version will be - created, and will be assigned the next sequential id within the - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_import_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ImportCryptoKeyVersionRequest( - rsa_aes_wrapped_key=b'rsa_aes_wrapped_key_blob', - parent="parent_value", - algorithm="EXTERNAL_SYMMETRIC_ENCRYPTION", - import_job="import_job_value", - ) - - # Make the request - response = await client.import_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest, dict]]): - The request object. Request message for - [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ImportCryptoKeyVersionRequest): - request = service.ImportCryptoKeyVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.import_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def create_import_job(self, - request: Optional[Union[service.CreateImportJobRequest, dict]] = None, - *, - parent: Optional[str] = None, - import_job_id: Optional[str] = None, - import_job: Optional[resources.ImportJob] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.ImportJob: - r"""Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] - is required. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_create_import_job(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - import_job = kms_v1.ImportJob() - import_job.import_method = "RSA_OAEP_4096_SHA256" - import_job.protection_level = "EXTERNAL_VPC" - - request = kms_v1.CreateImportJobRequest( - parent="parent_value", - import_job_id="import_job_id_value", - import_job=import_job, - ) - - # Make the request - response = await client.create_import_job(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.CreateImportJobRequest, dict]]): - The request object. Request message for - [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. - parent (:class:`str`): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the [KeyRing][google.cloud.kms.v1.KeyRing] associated - with the [ImportJobs][google.cloud.kms.v1.ImportJob]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - import_job_id (:class:`str`): - Required. It must be unique within a KeyRing and match - the regular expression ``[a-zA-Z0-9_-]{1,63}`` - - This corresponds to the ``import_job_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - import_job (:class:`google.cloud.kms_v1.types.ImportJob`): - Required. An [ImportJob][google.cloud.kms.v1.ImportJob] - with initial field values. - - This corresponds to the ``import_job`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - using pre-existing key material, generated outside of - Cloud KMS. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", - which is a public/private key pair. You use the - wrapping key to encrypt (also known as wrap) the - pre-existing key material to protect it during the - import process. The nature of the wrapping key - depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be - set to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be - used to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires - 3 days after it is created. Once expired, Cloud KMS - will no longer be able to import or unwrap any key - material that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public - key. - - For more information, see [Importing a - key](\ https://cloud.google.com/kms/docs/importing-a-key). - - """ - # Create or coerce a protobuf request object. - # - Quick 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, import_job_id, import_job]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.CreateImportJobRequest): - request = service.CreateImportJobRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if import_job_id is not None: - request.import_job_id = import_job_id - if import_job is not None: - request.import_job = import_job - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.create_import_job] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_crypto_key(self, - request: Optional[Union[service.UpdateCryptoKeyRequest, dict]] = None, - *, - crypto_key: Optional[resources.CryptoKey] = 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]] = (), - ) -> resources.CryptoKey: - r"""Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_update_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyRequest( - ) - - # Make the request - response = await client.update_crypto_key(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.UpdateCryptoKeyRequest, dict]]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. - crypto_key (:class:`google.cloud.kms_v1.types.CryptoKey`): - Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] - with updated values. - - This corresponds to the ``crypto_key`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that - can be used for cryptographic operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([crypto_key, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpdateCryptoKeyRequest): - request = service.UpdateCryptoKeyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if crypto_key is not None: - request.crypto_key = crypto_key - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_crypto_key] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("crypto_key.name", request.crypto_key.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_crypto_key_version(self, - request: Optional[Union[service.UpdateCryptoKeyVersionRequest, dict]] = None, - *, - crypto_key_version: Optional[resources.CryptoKeyVersion] = 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]] = (), - ) -> resources.CryptoKeyVersion: - r"""Update a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - metadata. - - [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be - changed between - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - and - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] - using this method. See - [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] - and - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - to move between other states. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_update_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyVersionRequest( - ) - - # Make the request - response = await client.update_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest, dict]]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. - crypto_key_version (:class:`google.cloud.kms_v1.types.CryptoKeyVersion`): - Required. - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with updated values. - - This corresponds to the ``crypto_key_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. List of fields to be - updated in this request. - - This corresponds to the ``update_mask`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([crypto_key_version, update_mask]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpdateCryptoKeyVersionRequest): - request = service.UpdateCryptoKeyVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if crypto_key_version is not None: - request.crypto_key_version = crypto_key_version - if update_mask is not None: - request.update_mask = update_mask - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("crypto_key_version.name", request.crypto_key_version.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_crypto_key_primary_version(self, - request: Optional[Union[service.UpdateCryptoKeyPrimaryVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - crypto_key_version_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Update the version of a - [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Returns an error if called on a key whose purpose is not - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_update_crypto_key_primary_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyPrimaryVersionRequest( - name="name_value", - crypto_key_version_id="crypto_key_version_id_value", - ) - - # Make the request - response = await client.update_crypto_key_primary_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest, dict]]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. - name (:class:`str`): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_version_id (:class:`str`): - Required. The id of the child - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use as primary. - - This corresponds to the ``crypto_key_version_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that - can be used for cryptographic operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, crypto_key_version_id]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpdateCryptoKeyPrimaryVersionRequest): - request = service.UpdateCryptoKeyPrimaryVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if crypto_key_version_id is not None: - request.crypto_key_version_id = crypto_key_version_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.update_crypto_key_primary_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def destroy_crypto_key_version(self, - request: Optional[Union[service.DestroyCryptoKeyVersionRequest, 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]] = (), - ) -> resources.CryptoKeyVersion: - r"""Schedule a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for - destruction. - - Upon calling this method, - [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] - will be set to - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be set to the time - [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] - in the future. At that time, the - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will - automatically change to - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], - and the key material will be irrevocably destroyed. - - Before the - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - is reached, - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - may be called to reverse the process. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_destroy_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.DestroyCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.destroy_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest, dict]]): - The request object. Request message for - [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to destroy. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.DestroyCryptoKeyVersionRequest): - request = service.DestroyCryptoKeyVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.destroy_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def restore_crypto_key_version(self, - request: Optional[Union[service.RestoreCryptoKeyVersionRequest, 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]] = (), - ) -> resources.CryptoKeyVersion: - r"""Restore a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] - state. - - Upon restoration of the CryptoKeyVersion, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be cleared. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_restore_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.RestoreCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.restore_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest, dict]]): - The request object. Request message for - [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to restore. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.RestoreCryptoKeyVersionRequest): - request = service.RestoreCryptoKeyVersionRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.restore_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def encrypt(self, - request: Optional[Union[service.EncryptRequest, dict]] = None, - *, - name: Optional[str] = None, - plaintext: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.EncryptResponse: - r"""Encrypts data, so that it can only be recovered by a call to - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_encrypt(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.EncryptRequest( - name="name_value", - plaintext=b'plaintext_blob', - ) - - # Make the request - response = await client.encrypt(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.EncryptRequest, dict]]): - The request object. Request message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - name (:class:`str`): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] or - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for encryption. - - If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is - specified, the server will use its [primary - version][google.cloud.kms.v1.CryptoKey.primary]. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - plaintext (:class:`bytes`): - Required. The data to encrypt. Must be no larger than - 64KiB. - - The maximum size depends on the key version's - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. - For - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE], - [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL], - and - [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] - keys, the plaintext must be no larger than 64KiB. For - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the - combined length of the plaintext and - additional_authenticated_data fields must be no larger - than 8KiB. - - This corresponds to the ``plaintext`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.EncryptResponse: - Response message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, plaintext]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.EncryptRequest): - request = service.EncryptRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if plaintext is not None: - request.plaintext = plaintext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.encrypt] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def decrypt(self, - request: Optional[Union[service.DecryptRequest, dict]] = None, - *, - name: Optional[str] = None, - ciphertext: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.DecryptResponse: - r"""Decrypts data that was protected by - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.DecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - ) - - # Make the request - response = await client.decrypt(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.DecryptRequest, dict]]): - The request object. Request message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - name (:class:`str`): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for - decryption. The server will choose the appropriate - version. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ciphertext (:class:`bytes`): - Required. The encrypted data originally returned in - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. - - This corresponds to the ``ciphertext`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.DecryptResponse: - Response message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, ciphertext]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.DecryptRequest): - request = service.DecryptRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if ciphertext is not None: - request.ciphertext = ciphertext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.decrypt] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def raw_encrypt(self, - request: Optional[Union[service.RawEncryptRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.RawEncryptResponse: - r"""Encrypts data using portable cryptographic primitives. Most - users should choose - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] and - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt] - rather than their raw counterparts. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_raw_encrypt(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.RawEncryptRequest( - name="name_value", - plaintext=b'plaintext_blob', - ) - - # Make the request - response = await client.raw_encrypt(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.RawEncryptRequest, dict]]): - The request object. Request message for - [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.RawEncryptResponse: - Response message for - [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.RawEncryptRequest): - request = service.RawEncryptRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.raw_encrypt] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def raw_decrypt(self, - request: Optional[Union[service.RawDecryptRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.RawDecryptResponse: - r"""Decrypts data that was originally encrypted using a raw - cryptographic mechanism. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_raw_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.RawDecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - initialization_vector=b'initialization_vector_blob', - ) - - # Make the request - response = await client.raw_decrypt(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.RawDecryptRequest, dict]]): - The request object. Request message for - [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.RawDecryptResponse: - Response message for - [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.RawDecryptRequest): - request = service.RawDecryptRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.raw_decrypt] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def asymmetric_sign(self, - request: Optional[Union[service.AsymmetricSignRequest, dict]] = None, - *, - name: Optional[str] = None, - digest: Optional[service.Digest] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.AsymmetricSignResponse: - r"""Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_SIGN, producing a signature that can be verified with - the public key retrieved from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_asymmetric_sign(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.AsymmetricSignRequest( - name="name_value", - ) - - # Make the request - response = await client.asymmetric_sign(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.AsymmetricSignRequest, dict]]): - The request object. Request message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for signing. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - digest (:class:`google.cloud.kms_v1.types.Digest`): - Optional. The digest of the data to sign. The digest - must be produced with the same digest algorithm as - specified by the key version's - [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. - - This field may not be supplied if - [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] - is supplied. - - This corresponds to the ``digest`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.AsymmetricSignResponse: - Response message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, digest]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.AsymmetricSignRequest): - request = service.AsymmetricSignRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if digest is not None: - request.digest = digest - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.asymmetric_sign] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def asymmetric_decrypt(self, - request: Optional[Union[service.AsymmetricDecryptRequest, dict]] = None, - *, - name: Optional[str] = None, - ciphertext: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.AsymmetricDecryptResponse: - r"""Decrypts data that was encrypted with a public key retrieved - from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] - corresponding to a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_DECRYPT. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_asymmetric_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.AsymmetricDecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - ) - - # Make the request - response = await client.asymmetric_decrypt(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.AsymmetricDecryptRequest, dict]]): - The request object. Request message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for decryption. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ciphertext (:class:`bytes`): - Required. The data encrypted with the named - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - public key using OAEP. - - This corresponds to the ``ciphertext`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.AsymmetricDecryptResponse: - Response message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, ciphertext]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.AsymmetricDecryptRequest): - request = service.AsymmetricDecryptRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if ciphertext is not None: - request.ciphertext = ciphertext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.asymmetric_decrypt] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def mac_sign(self, - request: Optional[Union[service.MacSignRequest, dict]] = None, - *, - name: Optional[str] = None, - data: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.MacSignResponse: - r"""Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - producing a tag that can be verified by another source with the - same key. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_mac_sign(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.MacSignRequest( - name="name_value", - data=b'data_blob', - ) - - # Make the request - response = await client.mac_sign(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.MacSignRequest, dict]]): - The request object. Request message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for signing. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (:class:`bytes`): - Required. The data to sign. The MAC - tag is computed over this data field - based on the specific algorithm. - - This corresponds to the ``data`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.MacSignResponse: - Response message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, data]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.MacSignRequest): - request = service.MacSignRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.mac_sign] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def mac_verify(self, - request: Optional[Union[service.MacVerifyRequest, dict]] = None, - *, - name: Optional[str] = None, - data: Optional[bytes] = None, - mac: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.MacVerifyResponse: - r"""Verifies MAC tag using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - and returns a response that indicates whether or not the - verification was successful. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - async def sample_mac_verify(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.MacVerifyRequest( - name="name_value", - data=b'data_blob', - mac=b'mac_blob', - ) - - # Make the request - response = await client.mac_verify(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.MacVerifyRequest, dict]]): - The request object. Request message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - name (:class:`str`): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for verification. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (:class:`bytes`): - Required. The data used previously as a - [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] - to generate the MAC tag. - - This corresponds to the ``data`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mac (:class:`bytes`): - Required. The signature to verify. - This corresponds to the ``mac`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.MacVerifyResponse: - Response message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, data, mac]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.MacVerifyRequest): - request = service.MacVerifyRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - if mac is not None: - request.mac = mac - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.mac_verify] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def generate_random_bytes(self, - request: Optional[Union[service.GenerateRandomBytesRequest, dict]] = None, - *, - location: Optional[str] = None, - length_bytes: Optional[int] = None, - protection_level: Optional[resources.ProtectionLevel] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.GenerateRandomBytesResponse: - r"""Generate random bytes using the Cloud KMS randomness - source in the 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 import kms_v1 - - async def sample_generate_random_bytes(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GenerateRandomBytesRequest( - ) - - # Make the request - response = await client.generate_random_bytes(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.cloud.kms_v1.types.GenerateRandomBytesRequest, dict]]): - The request object. Request message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - location (:class:`str`): - The project-specific location in - which to generate random bytes. For - example, - "projects/my-project/locations/us-central1". - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - length_bytes (:class:`int`): - The length in bytes of the amount of - randomness to retrieve. Minimum 8 - bytes, maximum 1024 bytes. - - This corresponds to the ``length_bytes`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - protection_level (:class:`google.cloud.kms_v1.types.ProtectionLevel`): - The - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - to use when generating the random data. Currently, only - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] - protection level is supported. - - This corresponds to the ``protection_level`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.GenerateRandomBytesResponse: - Response message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([location, length_bytes, protection_level]) - if request is not None and has_flattened_params: - raise ValueError("If the `request` argument is set, then none of " - "the individual field arguments should be set.") - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GenerateRandomBytesRequest): - request = service.GenerateRandomBytesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if length_bytes is not None: - request.length_bytes = length_bytes - if protection_level is not None: - request.protection_level = protection_level - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._client._transport._wrapped_methods[self._client._transport.generate_random_bytes] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("location", request.location), - )), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def get_operation( - self, - request: Optional[operations_pb2.GetOperationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operations_pb2.Operation: - r"""Gets the latest state of a long-running operation. - - Args: - request (:class:`~.operations_pb2.GetOperationRequest`): - The request object. Request message for - `GetOperation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.operations_pb2.Operation: - An ``Operation`` object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = operations_pb2.GetOperationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_location] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.list_locations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does - not have a policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified permissions against the IAM access control - policy for a function. - - If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~iam_policy_pb2.PolicyTestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self.transport._wrapped_methods[self._client._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def __aenter__(self) -> "KeyManagementServiceAsyncClient": - 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__ = ( - "KeyManagementServiceAsyncClient", -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/client.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/client.py deleted file mode 100644 index 2d95b5dc202f..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/client.py +++ /dev/null @@ -1,4517 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -import os -import re -from typing import Dict, Callable, Mapping, MutableMapping, MutableSequence, Optional, Sequence, Tuple, Type, Union, cast -import warnings - -from google.cloud.kms_v1 import gapic_version as package_version - -from google.api_core import client_options as client_options_lib -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - -from google.cloud.kms_v1.services.key_management_service import pagers -from google.cloud.kms_v1.types import resources -from google.cloud.kms_v1.types import service -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -from .transports.base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import KeyManagementServiceGrpcTransport -from .transports.grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport -from .transports.rest import KeyManagementServiceRestTransport - - -class KeyManagementServiceClientMeta(type): - """Metaclass for the KeyManagementService 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[KeyManagementServiceTransport]] - _transport_registry["grpc"] = KeyManagementServiceGrpcTransport - _transport_registry["grpc_asyncio"] = KeyManagementServiceGrpcAsyncIOTransport - _transport_registry["rest"] = KeyManagementServiceRestTransport - - def get_transport_class(cls, - label: Optional[str] = None, - ) -> Type[KeyManagementServiceTransport]: - """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 KeyManagementServiceClient(metaclass=KeyManagementServiceClientMeta): - """Google Cloud Key Management Service - - Manages cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [KeyRing][google.cloud.kms.v1.KeyRing] - - [CryptoKey][google.cloud.kms.v1.CryptoKey] - - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - - [ImportJob][google.cloud.kms.v1.ImportJob] - - If you are using manual gRPC libraries, see `Using gRPC with Cloud - KMS `__. - """ - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Converts api endpoint to mTLS endpoint. - - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. - DEFAULT_ENDPOINT = "cloudkms.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - _DEFAULT_ENDPOINT_TEMPLATE = "cloudkms.{UNIVERSE_DOMAIN}" - _DEFAULT_UNIVERSE = "googleapis.com" - - @classmethod - def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials - info. - - Args: - info (dict): The service account private key info. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - KeyManagementServiceClient: 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: - KeyManagementServiceClient: 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) -> KeyManagementServiceTransport: - """Returns the transport used by the client instance. - - Returns: - KeyManagementServiceTransport: The transport used by the client - instance. - """ - return self._transport - - @staticmethod - def crypto_key_path(project: str,location: str,key_ring: str,crypto_key: str,) -> str: - """Returns a fully-qualified crypto_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - - @staticmethod - def parse_crypto_key_path(path: str) -> Dict[str,str]: - """Parses a crypto_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def crypto_key_version_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: - """Returns a fully-qualified crypto_key_version string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) - - @staticmethod - def parse_crypto_key_version_path(path: str) -> Dict[str,str]: - """Parses a crypto_key_version path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def import_job_path(project: str,location: str,key_ring: str,import_job: str,) -> str: - """Returns a fully-qualified import_job string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format(project=project, location=location, key_ring=key_ring, import_job=import_job, ) - - @staticmethod - def parse_import_job_path(path: str) -> Dict[str,str]: - """Parses a import_job path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/importJobs/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def key_ring_path(project: str,location: str,key_ring: str,) -> str: - """Returns a fully-qualified key_ring string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}".format(project=project, location=location, key_ring=key_ring, ) - - @staticmethod - def parse_key_ring_path(path: str) -> Dict[str,str]: - """Parses a key_ring path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def public_key_path(project: str,location: str,key_ring: str,crypto_key: str,crypto_key_version: str,) -> str: - """Returns a fully-qualified public_key string.""" - return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) - - @staticmethod - def parse_public_key_path(path: str) -> Dict[str,str]: - """Parses a public_key path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)/publicKey$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_billing_account_path(billing_account: str, ) -> str: - """Returns a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str,str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str, ) -> str: - """Returns a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder, ) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str,str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str, ) -> str: - """Returns a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization, ) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str,str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str, ) -> str: - """Returns a fully-qualified project string.""" - return "projects/{project}".format(project=project, ) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str,str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str, ) -> str: - """Returns a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format(project=project, location=location, ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str,str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @classmethod - def get_mtls_endpoint_and_cert_source(cls, client_options: Optional[client_options_lib.ClientOptions] = None): - """Deprecated. Return the API endpoint and client cert source for mutual TLS. - - The client cert source is determined in the following order: - (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the - client cert source is None. - (2) if `client_options.client_cert_source` is provided, use the provided one; if the - default client cert source exists, use the default one; otherwise the client cert - source is None. - - The API endpoint is determined in the following order: - (1) if `client_options.api_endpoint` if provided, use the provided one. - (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variable is "never", use the default API - endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise - use the default API endpoint. - - More details can be found at https://google.aip.dev/auth/4114. - - Args: - client_options (google.api_core.client_options.ClientOptions): Custom options for the - client. Only the `api_endpoint` and `client_cert_source` properties may be used - in this method. - - Returns: - Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the - client cert source to use. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If any errors happen. - """ - - warnings.warn("get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", - DeprecationWarning) - if client_options is None: - client_options = client_options_lib.ClientOptions() - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - - # Figure out the client cert source to use. - client_cert_source = None - if use_client_cert == "true": - if client_options.client_cert_source: - client_cert_source = client_options.client_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - api_endpoint = cls.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = cls.DEFAULT_ENDPOINT - - return api_endpoint, client_cert_source - - @staticmethod - def _read_environment_variables(): - """Returns the environment variables used by the client. - - Returns: - Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, - GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. - - Raises: - ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not - any of ["true", "false"]. - google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT - is not any of ["auto", "never", "always"]. - """ - use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false").lower() - use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() - universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") - if use_client_cert not in ("true", "false"): - raise ValueError("Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`") - if use_mtls_endpoint not in ("auto", "never", "always"): - raise MutualTLSChannelError("Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`") - return use_client_cert == "true", use_mtls_endpoint, universe_domain_env - - @staticmethod - def _get_client_cert_source(provided_cert_source, use_cert_flag): - """Return the client cert source to be used by the client. - - Args: - provided_cert_source (bytes): The client certificate source provided. - use_cert_flag (bool): A flag indicating whether to use the client certificate. - - Returns: - bytes or None: The client cert source to be used by the client. - """ - client_cert_source = None - if use_cert_flag: - if provided_cert_source: - client_cert_source = provided_cert_source - elif mtls.has_default_client_cert_source(): - client_cert_source = mtls.default_client_cert_source() - return client_cert_source - - @staticmethod - def _get_api_endpoint(api_override, client_cert_source, universe_domain, use_mtls_endpoint): - """Return the API endpoint used by the client. - - Args: - api_override (str): The API endpoint override. If specified, this is always - the return value of this function and the other arguments are not used. - client_cert_source (bytes): The client certificate source used by the client. - universe_domain (str): The universe domain used by the client. - use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. - Possible values are "always", "auto", or "never". - - Returns: - str: The API endpoint to be used by the client. - """ - if api_override is not None: - api_endpoint = api_override - elif use_mtls_endpoint == "always" or (use_mtls_endpoint == "auto" and client_cert_source): - _default_universe = KeyManagementServiceClient._DEFAULT_UNIVERSE - if universe_domain != _default_universe: - raise MutualTLSChannelError(f"mTLS is not supported in any universe other than {_default_universe}.") - api_endpoint = KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=universe_domain) - return api_endpoint - - @staticmethod - def _get_universe_domain(client_universe_domain: Optional[str], universe_domain_env: Optional[str]) -> str: - """Return the universe domain used by the client. - - Args: - client_universe_domain (Optional[str]): The universe domain configured via the client options. - universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. - - Returns: - str: The universe domain to be used by the client. - - Raises: - ValueError: If the universe domain is an empty string. - """ - universe_domain = KeyManagementServiceClient._DEFAULT_UNIVERSE - if client_universe_domain is not None: - universe_domain = client_universe_domain - elif universe_domain_env is not None: - universe_domain = universe_domain_env - if len(universe_domain.strip()) == 0: - raise ValueError("Universe Domain cannot be an empty string.") - return universe_domain - - def _validate_universe_domain(self): - """Validates client's and credentials' universe domains are consistent. - - Returns: - bool: True iff the configured universe domain is valid. - - Raises: - ValueError: If the configured universe domain is not valid. - """ - - # NOTE (b/349488459): universe validation is disabled until further notice. - return True - - @property - def api_endpoint(self): - """Return the API endpoint used by the client instance. - - Returns: - str: The API endpoint used by the client instance. - """ - return self._api_endpoint - - @property - def universe_domain(self) -> str: - """Return the universe domain used by the client instance. - - Returns: - str: The universe domain used by the client instance. - """ - return self._universe_domain - - def __init__(self, *, - credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, KeyManagementServiceTransport, Callable[..., KeyManagementServiceTransport]]] = None, - client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiates the key management service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Optional[Union[str,KeyManagementServiceTransport,Callable[..., KeyManagementServiceTransport]]]): - The transport to use, or a Callable that constructs and returns a new transport. - If a Callable is given, it will be called with the same set of initialization - arguments as used in the KeyManagementServiceTransport constructor. - If set to None, a transport is chosen automatically. - client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): - Custom options for the client. - - 1. The ``api_endpoint`` property can be used to override the - default endpoint provided by the client when ``transport`` is - not explicitly provided. Only if this property is not set and - ``transport`` was not explicitly provided, the endpoint is - determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment - variable, which have one of the following values: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto-switch to the - default mTLS endpoint if client certificate is present; this is - the default value). - - 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide a client certificate for mTLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - 3. The ``universe_domain`` property can be used to override the - default "googleapis.com" universe. Note that the ``api_endpoint`` - property still takes precedence; and ``universe_domain`` is - currently not supported for mTLS. - - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - self._client_options = client_options - if isinstance(self._client_options, dict): - self._client_options = client_options_lib.from_dict(self._client_options) - if self._client_options is None: - self._client_options = client_options_lib.ClientOptions() - self._client_options = cast(client_options_lib.ClientOptions, self._client_options) - - universe_domain_opt = getattr(self._client_options, 'universe_domain', None) - - self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = KeyManagementServiceClient._read_environment_variables() - self._client_cert_source = KeyManagementServiceClient._get_client_cert_source(self._client_options.client_cert_source, self._use_client_cert) - self._universe_domain = KeyManagementServiceClient._get_universe_domain(universe_domain_opt, self._universe_domain_env) - self._api_endpoint = None # updated below, depending on `transport` - - # Initialize the universe domain validation. - self._is_universe_domain_valid = False - - api_key_value = getattr(self._client_options, "api_key", None) - if api_key_value and credentials: - raise ValueError("client_options.api_key and credentials are mutually exclusive") - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - transport_provided = isinstance(transport, KeyManagementServiceTransport) - if transport_provided: - # transport is a KeyManagementServiceTransport instance. - if credentials or self._client_options.credentials_file or api_key_value: - raise ValueError("When providing a transport instance, " - "provide its credentials directly.") - if self._client_options.scopes: - raise ValueError( - "When providing a transport instance, provide its scopes " - "directly." - ) - self._transport = cast(KeyManagementServiceTransport, transport) - self._api_endpoint = self._transport.host - - self._api_endpoint = (self._api_endpoint or - KeyManagementServiceClient._get_api_endpoint( - self._client_options.api_endpoint, - self._client_cert_source, - self._universe_domain, - self._use_mtls_endpoint)) - - if not transport_provided: - import google.auth._default # type: ignore - - if api_key_value and hasattr(google.auth._default, "get_api_key_credentials"): - credentials = google.auth._default.get_api_key_credentials(api_key_value) - - transport_init: Union[Type[KeyManagementServiceTransport], Callable[..., KeyManagementServiceTransport]] = ( - KeyManagementServiceClient.get_transport_class(transport) - if isinstance(transport, str) or transport is None - else cast(Callable[..., KeyManagementServiceTransport], transport) - ) - # initialize with the provided callable or the passed in class - self._transport = transport_init( - credentials=credentials, - credentials_file=self._client_options.credentials_file, - host=self._api_endpoint, - scopes=self._client_options.scopes, - client_cert_source_for_mtls=self._client_cert_source, - quota_project_id=self._client_options.quota_project_id, - client_info=client_info, - always_use_jwt_access=True, - api_audience=self._client_options.api_audience, - ) - - def list_key_rings(self, - request: Optional[Union[service.ListKeyRingsRequest, 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.ListKeyRingsPager: - r"""Lists [KeyRings][google.cloud.kms.v1.KeyRing]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_list_key_rings(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.ListKeyRingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_key_rings(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.ListKeyRingsRequest, dict]): - The request object. Request message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - parent (str): - Required. The resource name of the location associated - with the [KeyRings][google.cloud.kms.v1.KeyRing], in the - format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.services.key_management_service.pagers.ListKeyRingsPager: - Response message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListKeyRingsRequest): - request = service.ListKeyRingsRequest(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_key_rings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListKeyRingsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_crypto_keys(self, - request: Optional[Union[service.ListCryptoKeysRequest, 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.ListCryptoKeysPager: - r"""Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_list_crypto_keys(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.ListCryptoKeysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crypto_keys(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.ListCryptoKeysRequest, dict]): - The request object. Request message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - parent (str): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - - 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.kms_v1.services.key_management_service.pagers.ListCryptoKeysPager: - Response message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListCryptoKeysRequest): - request = service.ListCryptoKeysRequest(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_crypto_keys] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCryptoKeysPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_crypto_key_versions(self, - request: Optional[Union[service.ListCryptoKeyVersionsRequest, 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.ListCryptoKeyVersionsPager: - r"""Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_list_crypto_key_versions(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.ListCryptoKeyVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crypto_key_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest, dict]): - The request object. Request message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - parent (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in - the format - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - - 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.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsPager: - Response message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListCryptoKeyVersionsRequest): - request = service.ListCryptoKeyVersionsRequest(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_crypto_key_versions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListCryptoKeyVersionsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def list_import_jobs(self, - request: Optional[Union[service.ListImportJobsRequest, 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.ListImportJobsPager: - r"""Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_list_import_jobs(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.ListImportJobsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_import_jobs(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.ListImportJobsRequest, dict]): - The request object. Request message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - parent (str): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - - 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.kms_v1.services.key_management_service.pagers.ListImportJobsPager: - Response message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ListImportJobsRequest): - request = service.ListImportJobsRequest(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_import_jobs] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListImportJobsPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_key_ring(self, - request: Optional[Union[service.GetKeyRingRequest, 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]] = (), - ) -> resources.KeyRing: - r"""Returns metadata for a given - [KeyRing][google.cloud.kms.v1.KeyRing]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_get_key_ring(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetKeyRingRequest( - name="name_value", - ) - - # Make the request - response = client.get_key_ring(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.GetKeyRingRequest, dict]): - The request object. Request message for - [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. - name (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the [KeyRing][google.cloud.kms.v1.KeyRing] to get. - - 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.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetKeyRingRequest): - request = service.GetKeyRingRequest(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_key_ring] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_crypto_key(self, - request: Optional[Union[service.GetCryptoKeyRequest, 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]] = (), - ) -> resources.CryptoKey: - r"""Returns metadata for a given - [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its - [primary][google.cloud.kms.v1.CryptoKey.primary] - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_get_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetCryptoKeyRequest( - name="name_value", - ) - - # Make the request - response = client.get_crypto_key(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.GetCryptoKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. - name (str): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] - of the [CryptoKey][google.cloud.kms.v1.CryptoKey] to - get. - - 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.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that - can be used for cryptographic operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetCryptoKeyRequest): - request = service.GetCryptoKeyRequest(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_crypto_key] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_crypto_key_version(self, - request: Optional[Union[service.GetCryptoKeyVersionRequest, 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]] = (), - ) -> resources.CryptoKeyVersion: - r"""Returns metadata for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_get_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.GetCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. - name (str): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to get. - - 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.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetCryptoKeyVersionRequest): - request = service.GetCryptoKeyVersionRequest(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_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_public_key(self, - request: Optional[Union[service.GetPublicKeyRequest, 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]] = (), - ) -> resources.PublicKey: - r"""Returns the public key for the given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] - or - [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_get_public_key(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetPublicKeyRequest( - name="name_value", - ) - - # Make the request - response = client.get_public_key(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.GetPublicKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - name (str): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - public key to get. - - 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.kms_v1.types.PublicKey: - The public keys for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - Obtained via - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetPublicKeyRequest): - request = service.GetPublicKeyRequest(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_public_key] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def get_import_job(self, - request: Optional[Union[service.GetImportJobRequest, 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]] = (), - ) -> resources.ImportJob: - r"""Returns metadata for a given - [ImportJob][google.cloud.kms.v1.ImportJob]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_get_import_job(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetImportJobRequest( - name="name_value", - ) - - # Make the request - response = client.get_import_job(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.GetImportJobRequest, dict]): - The request object. Request message for - [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. - name (str): - Required. The [name][google.cloud.kms.v1.ImportJob.name] - of the [ImportJob][google.cloud.kms.v1.ImportJob] to - get. - - 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.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - using pre-existing key material, generated outside of - Cloud KMS. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", - which is a public/private key pair. You use the - wrapping key to encrypt (also known as wrap) the - pre-existing key material to protect it during the - import process. The nature of the wrapping key - depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be - set to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be - used to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires - 3 days after it is created. Once expired, Cloud KMS - will no longer be able to import or unwrap any key - material that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public - key. - - For more information, see [Importing a - key](\ https://cloud.google.com/kms/docs/importing-a-key). - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GetImportJobRequest): - request = service.GetImportJobRequest(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_import_job] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_key_ring(self, - request: Optional[Union[service.CreateKeyRingRequest, dict]] = None, - *, - parent: Optional[str] = None, - key_ring_id: Optional[str] = None, - key_ring: Optional[resources.KeyRing] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.KeyRing: - r"""Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given - Project and Location. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_create_key_ring(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.CreateKeyRingRequest( - parent="parent_value", - key_ring_id="key_ring_id_value", - ) - - # Make the request - response = client.create_key_ring(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.CreateKeyRingRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. - parent (str): - Required. The resource name of the location associated - with the [KeyRings][google.cloud.kms.v1.KeyRing], in the - format ``projects/*/locations/*``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_ring_id (str): - Required. It must be unique within a location and match - the regular expression ``[a-zA-Z0-9_-]{1,63}`` - - This corresponds to the ``key_ring_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - key_ring (google.cloud.kms_v1.types.KeyRing): - Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with - initial field values. - - This corresponds to the ``key_ring`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, key_ring_id, key_ring]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.CreateKeyRingRequest): - request = service.CreateKeyRingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if key_ring_id is not None: - request.key_ring_id = key_ring_id - if key_ring is not None: - request.key_ring = key_ring - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_key_ring] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_crypto_key(self, - request: Optional[Union[service.CreateCryptoKeyRequest, dict]] = None, - *, - parent: Optional[str] = None, - crypto_key_id: Optional[str] = None, - crypto_key: Optional[resources.CryptoKey] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and - [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] - are required. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_create_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.CreateCryptoKeyRequest( - parent="parent_value", - crypto_key_id="crypto_key_id_value", - ) - - # Make the request - response = client.create_crypto_key(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.CreateCryptoKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. - parent (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the KeyRing associated with the - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_id (str): - Required. It must be unique within a KeyRing and match - the regular expression ``[a-zA-Z0-9_-]{1,63}`` - - This corresponds to the ``crypto_key_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key (google.cloud.kms_v1.types.CryptoKey): - Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] - with initial field values. - - This corresponds to the ``crypto_key`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that - can be used for cryptographic operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, crypto_key_id, crypto_key]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.CreateCryptoKeyRequest): - request = service.CreateCryptoKeyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if crypto_key_id is not None: - request.crypto_key_id = crypto_key_id - if crypto_key is not None: - request.crypto_key = crypto_key - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_crypto_key] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_crypto_key_version(self, - request: Optional[Union[service.CreateCryptoKeyVersionRequest, dict]] = None, - *, - parent: Optional[str] = None, - crypto_key_version: Optional[resources.CryptoKeyVersion] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Create a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - The server will assign the next sequential id. If unset, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_create_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.CreateCryptoKeyVersionRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. - parent (str): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] - of the [CryptoKey][google.cloud.kms.v1.CryptoKey] - associated with the - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): - Required. A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with initial field values. - - This corresponds to the ``crypto_key_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, crypto_key_version]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.CreateCryptoKeyVersionRequest): - request = service.CreateCryptoKeyVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if crypto_key_version is not None: - request.crypto_key_version = crypto_key_version - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def import_crypto_key_version(self, - request: Optional[Union[service.ImportCryptoKeyVersionRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKeyVersion: - r"""Import wrapped key material into a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - All requests must specify a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is - additionally specified in the request, key material will be - reimported into that version. Otherwise, a new version will be - created, and will be assigned the next sequential id within the - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_import_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.ImportCryptoKeyVersionRequest( - rsa_aes_wrapped_key=b'rsa_aes_wrapped_key_blob', - parent="parent_value", - algorithm="EXTERNAL_SYMMETRIC_ENCRYPTION", - import_job="import_job_value", - ) - - # Make the request - response = client.import_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.ImportCryptoKeyVersionRequest): - request = service.ImportCryptoKeyVersionRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.import_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def create_import_job(self, - request: Optional[Union[service.CreateImportJobRequest, dict]] = None, - *, - parent: Optional[str] = None, - import_job_id: Optional[str] = None, - import_job: Optional[resources.ImportJob] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.ImportJob: - r"""Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] - is required. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_create_import_job(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - import_job = kms_v1.ImportJob() - import_job.import_method = "RSA_OAEP_4096_SHA256" - import_job.protection_level = "EXTERNAL_VPC" - - request = kms_v1.CreateImportJobRequest( - parent="parent_value", - import_job_id="import_job_id_value", - import_job=import_job, - ) - - # Make the request - response = client.create_import_job(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.CreateImportJobRequest, dict]): - The request object. Request message for - [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. - parent (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] - of the [KeyRing][google.cloud.kms.v1.KeyRing] associated - with the [ImportJobs][google.cloud.kms.v1.ImportJob]. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - import_job_id (str): - Required. It must be unique within a KeyRing and match - the regular expression ``[a-zA-Z0-9_-]{1,63}`` - - This corresponds to the ``import_job_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - import_job (google.cloud.kms_v1.types.ImportJob): - Required. An [ImportJob][google.cloud.kms.v1.ImportJob] - with initial field values. - - This corresponds to the ``import_job`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - using pre-existing key material, generated outside of - Cloud KMS. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", - which is a public/private key pair. You use the - wrapping key to encrypt (also known as wrap) the - pre-existing key material to protect it during the - import process. The nature of the wrapping key - depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be - set to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be - used to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires - 3 days after it is created. Once expired, Cloud KMS - will no longer be able to import or unwrap any key - material that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public - key. - - For more information, see [Importing a - key](\ https://cloud.google.com/kms/docs/importing-a-key). - - """ - # Create or coerce a protobuf request object. - # - Quick 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, import_job_id, import_job]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.CreateImportJobRequest): - request = service.CreateImportJobRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - if import_job_id is not None: - request.import_job_id = import_job_id - if import_job is not None: - request.import_job = import_job - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_import_job] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("parent", request.parent), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_crypto_key(self, - request: Optional[Union[service.UpdateCryptoKeyRequest, dict]] = None, - *, - crypto_key: Optional[resources.CryptoKey] = 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]] = (), - ) -> resources.CryptoKey: - r"""Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_update_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyRequest( - ) - - # Make the request - response = client.update_crypto_key(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyRequest, dict]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. - crypto_key (google.cloud.kms_v1.types.CryptoKey): - Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] - with updated values. - - This corresponds to the ``crypto_key`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be - updated in this request. - - 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.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that - can be used for cryptographic operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([crypto_key, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpdateCryptoKeyRequest): - request = service.UpdateCryptoKeyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if crypto_key is not None: - request.crypto_key = crypto_key - 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_crypto_key] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("crypto_key.name", request.crypto_key.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_crypto_key_version(self, - request: Optional[Union[service.UpdateCryptoKeyVersionRequest, dict]] = None, - *, - crypto_key_version: Optional[resources.CryptoKeyVersion] = 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]] = (), - ) -> resources.CryptoKeyVersion: - r"""Update a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - metadata. - - [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be - changed between - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - and - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] - using this method. See - [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] - and - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - to move between other states. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_update_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyVersionRequest( - ) - - # Make the request - response = client.update_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. - crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): - Required. - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with updated values. - - This corresponds to the ``crypto_key_version`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be - updated in this request. - - 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.cloud.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([crypto_key_version, update_mask]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpdateCryptoKeyVersionRequest): - request = service.UpdateCryptoKeyVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if crypto_key_version is not None: - request.crypto_key_version = crypto_key_version - 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_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("crypto_key_version.name", request.crypto_key_version.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def update_crypto_key_primary_version(self, - request: Optional[Union[service.UpdateCryptoKeyPrimaryVersionRequest, dict]] = None, - *, - name: Optional[str] = None, - crypto_key_version_id: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> resources.CryptoKey: - r"""Update the version of a - [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Returns an error if called on a key whose purpose is not - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_update_crypto_key_primary_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyPrimaryVersionRequest( - name="name_value", - crypto_key_version_id="crypto_key_version_id_value", - ) - - # Make the request - response = client.update_crypto_key_primary_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - crypto_key_version_id (str): - Required. The id of the child - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use as primary. - - This corresponds to the ``crypto_key_version_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical key that - can be used for cryptographic operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made - up of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], - which represent the actual key material used in - cryptographic operations. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, crypto_key_version_id]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.UpdateCryptoKeyPrimaryVersionRequest): - request = service.UpdateCryptoKeyPrimaryVersionRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if crypto_key_version_id is not None: - request.crypto_key_version_id = crypto_key_version_id - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_crypto_key_primary_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def destroy_crypto_key_version(self, - request: Optional[Union[service.DestroyCryptoKeyVersionRequest, 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]] = (), - ) -> resources.CryptoKeyVersion: - r"""Schedule a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for - destruction. - - Upon calling this method, - [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] - will be set to - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be set to the time - [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] - in the future. At that time, the - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will - automatically change to - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], - and the key material will be irrevocably destroyed. - - Before the - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - is reached, - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - may be called to reverse the process. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_destroy_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.DestroyCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = client.destroy_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to destroy. - - 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.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.DestroyCryptoKeyVersionRequest): - request = service.DestroyCryptoKeyVersionRequest(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.destroy_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def restore_crypto_key_version(self, - request: Optional[Union[service.RestoreCryptoKeyVersionRequest, 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]] = (), - ) -> resources.CryptoKeyVersion: - r"""Restore a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] - state. - - Upon restoration of the CryptoKeyVersion, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be cleared. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_restore_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.RestoreCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = client.restore_crypto_key_version(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest, dict]): - The request object. Request message for - [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to restore. - - 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.kms_v1.types.CryptoKeyVersion: - A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an - individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key - material represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used - to encrypt, decrypt, or sign data when an authorized - user or application invokes Cloud KMS. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.RestoreCryptoKeyVersionRequest): - request = service.RestoreCryptoKeyVersionRequest(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.restore_crypto_key_version] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def encrypt(self, - request: Optional[Union[service.EncryptRequest, dict]] = None, - *, - name: Optional[str] = None, - plaintext: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.EncryptResponse: - r"""Encrypts data, so that it can only be recovered by a call to - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_encrypt(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.EncryptRequest( - name="name_value", - plaintext=b'plaintext_blob', - ) - - # Make the request - response = client.encrypt(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.EncryptRequest, dict]): - The request object. Request message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] or - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for encryption. - - If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is - specified, the server will use its [primary - version][google.cloud.kms.v1.CryptoKey.primary]. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - plaintext (bytes): - Required. The data to encrypt. Must be no larger than - 64KiB. - - The maximum size depends on the key version's - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. - For - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE], - [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL], - and - [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] - keys, the plaintext must be no larger than 64KiB. For - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the - combined length of the plaintext and - additional_authenticated_data fields must be no larger - than 8KiB. - - This corresponds to the ``plaintext`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.EncryptResponse: - Response message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, plaintext]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.EncryptRequest): - request = service.EncryptRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if plaintext is not None: - request.plaintext = plaintext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.encrypt] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def decrypt(self, - request: Optional[Union[service.DecryptRequest, dict]] = None, - *, - name: Optional[str] = None, - ciphertext: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.DecryptResponse: - r"""Decrypts data that was protected by - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.DecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - ) - - # Make the request - response = client.decrypt(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.DecryptRequest, dict]): - The request object. Request message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for - decryption. The server will choose the appropriate - version. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ciphertext (bytes): - Required. The encrypted data originally returned in - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. - - This corresponds to the ``ciphertext`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.DecryptResponse: - Response message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, ciphertext]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.DecryptRequest): - request = service.DecryptRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if ciphertext is not None: - request.ciphertext = ciphertext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.decrypt] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def raw_encrypt(self, - request: Optional[Union[service.RawEncryptRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.RawEncryptResponse: - r"""Encrypts data using portable cryptographic primitives. Most - users should choose - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] and - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt] - rather than their raw counterparts. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_raw_encrypt(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.RawEncryptRequest( - name="name_value", - plaintext=b'plaintext_blob', - ) - - # Make the request - response = client.raw_encrypt(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.RawEncryptRequest, dict]): - The request object. Request message for - [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.RawEncryptResponse: - Response message for - [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.RawEncryptRequest): - request = service.RawEncryptRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.raw_encrypt] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def raw_decrypt(self, - request: Optional[Union[service.RawDecryptRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.RawDecryptResponse: - r"""Decrypts data that was originally encrypted using a raw - cryptographic mechanism. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_raw_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.RawDecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - initialization_vector=b'initialization_vector_blob', - ) - - # Make the request - response = client.raw_decrypt(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.RawDecryptRequest, dict]): - The request object. Request message for - [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.RawDecryptResponse: - Response message for - [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. - - """ - # Create or coerce a protobuf request object. - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.RawDecryptRequest): - request = service.RawDecryptRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.raw_decrypt] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def asymmetric_sign(self, - request: Optional[Union[service.AsymmetricSignRequest, dict]] = None, - *, - name: Optional[str] = None, - digest: Optional[service.Digest] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.AsymmetricSignResponse: - r"""Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_SIGN, producing a signature that can be verified with - the public key retrieved from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_asymmetric_sign(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.AsymmetricSignRequest( - name="name_value", - ) - - # Make the request - response = client.asymmetric_sign(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.AsymmetricSignRequest, dict]): - The request object. Request message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for signing. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - digest (google.cloud.kms_v1.types.Digest): - Optional. The digest of the data to sign. The digest - must be produced with the same digest algorithm as - specified by the key version's - [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. - - This field may not be supplied if - [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] - is supplied. - - This corresponds to the ``digest`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.AsymmetricSignResponse: - Response message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, digest]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.AsymmetricSignRequest): - request = service.AsymmetricSignRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if digest is not None: - request.digest = digest - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.asymmetric_sign] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def asymmetric_decrypt(self, - request: Optional[Union[service.AsymmetricDecryptRequest, dict]] = None, - *, - name: Optional[str] = None, - ciphertext: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.AsymmetricDecryptResponse: - r"""Decrypts data that was encrypted with a public key retrieved - from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] - corresponding to a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_DECRYPT. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_asymmetric_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.AsymmetricDecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - ) - - # Make the request - response = client.asymmetric_decrypt(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.AsymmetricDecryptRequest, dict]): - The request object. Request message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for decryption. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - ciphertext (bytes): - Required. The data encrypted with the named - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - public key using OAEP. - - This corresponds to the ``ciphertext`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.AsymmetricDecryptResponse: - Response message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, ciphertext]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.AsymmetricDecryptRequest): - request = service.AsymmetricDecryptRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if ciphertext is not None: - request.ciphertext = ciphertext - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.asymmetric_decrypt] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def mac_sign(self, - request: Optional[Union[service.MacSignRequest, dict]] = None, - *, - name: Optional[str] = None, - data: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.MacSignResponse: - r"""Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - producing a tag that can be verified by another source with the - same key. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_mac_sign(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.MacSignRequest( - name="name_value", - data=b'data_blob', - ) - - # Make the request - response = client.mac_sign(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.MacSignRequest, dict]): - The request object. Request message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for signing. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (bytes): - Required. The data to sign. The MAC - tag is computed over this data field - based on the specific algorithm. - - This corresponds to the ``data`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.MacSignResponse: - Response message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, data]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.MacSignRequest): - request = service.MacSignRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.mac_sign] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def mac_verify(self, - request: Optional[Union[service.MacVerifyRequest, dict]] = None, - *, - name: Optional[str] = None, - data: Optional[bytes] = None, - mac: Optional[bytes] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.MacVerifyResponse: - r"""Verifies MAC tag using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - and returns a response that indicates whether or not the - verification was successful. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.cloud import kms_v1 - - def sample_mac_verify(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.MacVerifyRequest( - name="name_value", - data=b'data_blob', - mac=b'mac_blob', - ) - - # Make the request - response = client.mac_verify(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.MacVerifyRequest, dict]): - The request object. Request message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - to use for verification. - - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - data (bytes): - Required. The data used previously as a - [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] - to generate the MAC tag. - - This corresponds to the ``data`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - mac (bytes): - Required. The signature to verify. - This corresponds to the ``mac`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.MacVerifyResponse: - Response message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - - """ - # Create or coerce a protobuf request object. - # - Quick 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, data, mac]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.MacVerifyRequest): - request = service.MacVerifyRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if name is not None: - request.name = name - if data is not None: - request.data = data - if mac is not None: - request.mac = mac - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.mac_verify] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("name", request.name), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def generate_random_bytes(self, - request: Optional[Union[service.GenerateRandomBytesRequest, dict]] = None, - *, - location: Optional[str] = None, - length_bytes: Optional[int] = None, - protection_level: Optional[resources.ProtectionLevel] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> service.GenerateRandomBytesResponse: - r"""Generate random bytes using the Cloud KMS randomness - source in the 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 import kms_v1 - - def sample_generate_random_bytes(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GenerateRandomBytesRequest( - ) - - # Make the request - response = client.generate_random_bytes(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.cloud.kms_v1.types.GenerateRandomBytesRequest, dict]): - The request object. Request message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - location (str): - The project-specific location in - which to generate random bytes. For - example, - "projects/my-project/locations/us-central1". - - This corresponds to the ``location`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - length_bytes (int): - The length in bytes of the amount of - randomness to retrieve. Minimum 8 - bytes, maximum 1024 bytes. - - This corresponds to the ``length_bytes`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - to use when generating the random data. Currently, only - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] - protection level is supported. - - This corresponds to the ``protection_level`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.cloud.kms_v1.types.GenerateRandomBytesResponse: - Response message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - - """ - # Create or coerce a protobuf request object. - # - Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([location, length_bytes, protection_level]) - if request is not None and has_flattened_params: - raise ValueError('If the `request` argument is set, then none of ' - 'the individual field arguments should be set.') - - # - Use the request object if provided (there's no risk of modifying the input as - # there are no flattened fields), or create one. - if not isinstance(request, service.GenerateRandomBytesRequest): - request = service.GenerateRandomBytesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if location is not None: - request.location = location - if length_bytes is not None: - request.length_bytes = length_bytes - if protection_level is not None: - request.protection_level = protection_level - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.generate_random_bytes] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ("location", request.location), - )), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - def __enter__(self) -> "KeyManagementServiceClient": - 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 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 = self._transport._wrapped_methods[self._transport.get_operation] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_location( - self, - request: Optional[locations_pb2.GetLocationRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.Location: - r"""Gets information about a location. - - Args: - request (:class:`~.location_pb2.GetLocationRequest`): - The request object. Request message for - `GetLocation` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.Location: - Location object. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.GetLocationRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_location] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def list_locations( - self, - request: Optional[locations_pb2.ListLocationsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> locations_pb2.ListLocationsResponse: - r"""Lists information about the supported locations for this service. - - Args: - request (:class:`~.location_pb2.ListLocationsRequest`): - The request object. Request message for - `ListLocations` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.location_pb2.ListLocationsResponse: - Response message for ``ListLocations`` method. - """ - # Create or coerce a protobuf request object. - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = locations_pb2.ListLocationsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_locations] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("name", request.name),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Sets the IAM access control policy on the specified function. - - Replaces any existing policy. - - Args: - request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.SetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy_pb2.Policy: - r"""Gets the IAM access control policy for a function. - - Returns an empty policy if the function exists and does not have a - policy set. - - Args: - request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - retry (google.api_core.retry.Retry): Designation of what errors, if - any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.policy_pb2.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.GetIamPolicyRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - r"""Tests the specified IAM permissions against the IAM access control - policy for a function. - - If the function does not exist, this will return an empty set - of permissions, not a NOT_FOUND error. - - Args: - request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - Returns: - ~.iam_policy_pb2.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy_pb2.TestIamPermissionsRequest(**request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("resource", request.resource),)), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -__all__ = ( - "KeyManagementServiceClient", -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/pagers.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/pagers.py deleted file mode 100644 index efdfd7733d45..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/pagers.py +++ /dev/null @@ -1,568 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from google.api_core import gapic_v1 -from google.api_core import retry as retries -from google.api_core import retry_async as retries_async -from typing import Any, AsyncIterator, Awaitable, Callable, Sequence, Tuple, Optional, Iterator, Union -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] - OptionalAsyncRetry = Union[retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore - -from google.cloud.kms_v1.types import resources -from google.cloud.kms_v1.types import service - - -class ListKeyRingsPager: - """A pager for iterating through ``list_key_rings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``key_rings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListKeyRings`` requests and continue to iterate - through the ``key_rings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., service.ListKeyRingsResponse], - request: service.ListKeyRingsRequest, - response: service.ListKeyRingsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListKeyRingsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListKeyRingsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListKeyRingsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListKeyRingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[resources.KeyRing]: - for page in self.pages: - yield from page.key_rings - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListKeyRingsAsyncPager: - """A pager for iterating through ``list_key_rings`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``key_rings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListKeyRings`` requests and continue to iterate - through the ``key_rings`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListKeyRingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[service.ListKeyRingsResponse]], - request: service.ListKeyRingsRequest, - response: service.ListKeyRingsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListKeyRingsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListKeyRingsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListKeyRingsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListKeyRingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[resources.KeyRing]: - async def async_generator(): - async for page in self.pages: - for response in page.key_rings: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCryptoKeysPager: - """A pager for iterating through ``list_crypto_keys`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` object, and - provides an ``__iter__`` method to iterate through its - ``crypto_keys`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCryptoKeys`` requests and continue to iterate - through the ``crypto_keys`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., service.ListCryptoKeysResponse], - request: service.ListCryptoKeysRequest, - response: service.ListCryptoKeysResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListCryptoKeysRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListCryptoKeysResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListCryptoKeysRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListCryptoKeysResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[resources.CryptoKey]: - for page in self.pages: - yield from page.crypto_keys - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCryptoKeysAsyncPager: - """A pager for iterating through ``list_crypto_keys`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``crypto_keys`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCryptoKeys`` requests and continue to iterate - through the ``crypto_keys`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeysResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[service.ListCryptoKeysResponse]], - request: service.ListCryptoKeysRequest, - response: service.ListCryptoKeysResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListCryptoKeysRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListCryptoKeysResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListCryptoKeysRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListCryptoKeysResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[resources.CryptoKey]: - async def async_generator(): - async for page in self.pages: - for response in page.crypto_keys: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCryptoKeyVersionsPager: - """A pager for iterating through ``list_crypto_key_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``crypto_key_versions`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListCryptoKeyVersions`` requests and continue to iterate - through the ``crypto_key_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., service.ListCryptoKeyVersionsResponse], - request: service.ListCryptoKeyVersionsRequest, - response: service.ListCryptoKeyVersionsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListCryptoKeyVersionsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListCryptoKeyVersionsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListCryptoKeyVersionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[resources.CryptoKeyVersion]: - for page in self.pages: - yield from page.crypto_key_versions - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListCryptoKeyVersionsAsyncPager: - """A pager for iterating through ``list_crypto_key_versions`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``crypto_key_versions`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListCryptoKeyVersions`` requests and continue to iterate - through the ``crypto_key_versions`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[service.ListCryptoKeyVersionsResponse]], - request: service.ListCryptoKeyVersionsRequest, - response: service.ListCryptoKeyVersionsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListCryptoKeyVersionsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListCryptoKeyVersionsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListCryptoKeyVersionsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListCryptoKeyVersionsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[resources.CryptoKeyVersion]: - async def async_generator(): - async for page in self.pages: - for response in page.crypto_key_versions: - yield response - - return async_generator() - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListImportJobsPager: - """A pager for iterating through ``list_import_jobs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListImportJobsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``import_jobs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListImportJobs`` requests and continue to iterate - through the ``import_jobs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListImportJobsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., service.ListImportJobsResponse], - request: service.ListImportJobsRequest, - response: service.ListImportJobsResponse, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListImportJobsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListImportJobsResponse): - The initial response object. - retry (google.api_core.retry.Retry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListImportJobsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[service.ListImportJobsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[resources.ImportJob]: - for page in self.pages: - yield from page.import_jobs - - def __repr__(self) -> str: - return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) - - -class ListImportJobsAsyncPager: - """A pager for iterating through ``list_import_jobs`` requests. - - This class thinly wraps an initial - :class:`google.cloud.kms_v1.types.ListImportJobsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``import_jobs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListImportJobs`` requests and continue to iterate - through the ``import_jobs`` field on the - corresponding responses. - - All the usual :class:`google.cloud.kms_v1.types.ListImportJobsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - def __init__(self, - method: Callable[..., Awaitable[service.ListImportJobsResponse]], - request: service.ListImportJobsRequest, - response: service.ListImportJobsResponse, - *, - retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - 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.kms_v1.types.ListImportJobsRequest): - The initial request object. - response (google.cloud.kms_v1.types.ListImportJobsResponse): - The initial response object. - retry (google.api_core.retry.AsyncRetry): Designation of what errors, - if any, should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = service.ListImportJobsRequest(request) - self._response = response - self._retry = retry - self._timeout = timeout - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[service.ListImportJobsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, retry=self._retry, timeout=self._timeout, metadata=self._metadata) - yield self._response - def __aiter__(self) -> AsyncIterator[resources.ImportJob]: - async def async_generator(): - async for page in self.pages: - for response in page.import_jobs: - 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-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/README.rst b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/README.rst deleted file mode 100644 index ebe015054ce3..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/README.rst +++ /dev/null @@ -1,9 +0,0 @@ - -transport inheritance structure -_______________________________ - -`KeyManagementServiceTransport` is the ABC for all transports. -- public child `KeyManagementServiceGrpcTransport` for sync gRPC transport (defined in `grpc.py`). -- public child `KeyManagementServiceGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). -- private child `_BaseKeyManagementServiceRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). -- public child `KeyManagementServiceRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py deleted file mode 100644 index d2742fe4c9e0..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/__init__.py +++ /dev/null @@ -1,38 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from collections import OrderedDict -from typing import Dict, Type - -from .base import KeyManagementServiceTransport -from .grpc import KeyManagementServiceGrpcTransport -from .grpc_asyncio import KeyManagementServiceGrpcAsyncIOTransport -from .rest import KeyManagementServiceRestTransport -from .rest import KeyManagementServiceRestInterceptor - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[KeyManagementServiceTransport]] -_transport_registry['grpc'] = KeyManagementServiceGrpcTransport -_transport_registry['grpc_asyncio'] = KeyManagementServiceGrpcAsyncIOTransport -_transport_registry['rest'] = KeyManagementServiceRestTransport - -__all__ = ( - 'KeyManagementServiceTransport', - 'KeyManagementServiceGrpcTransport', - 'KeyManagementServiceGrpcAsyncIOTransport', - 'KeyManagementServiceRestTransport', - 'KeyManagementServiceRestInterceptor', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py deleted file mode 100644 index dbfd1ea5078b..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/base.py +++ /dev/null @@ -1,863 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import abc -from typing import Awaitable, Callable, Dict, Optional, Sequence, Union - -from google.cloud.kms_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.kms_v1.types import resources -from google.cloud.kms_v1.types import service -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(gapic_version=package_version.__version__) - - -class KeyManagementServiceTransport(abc.ABC): - """Abstract transport class for KeyManagementService.""" - - AUTH_SCOPES = ( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', - ) - - DEFAULT_HOST: str = 'cloudkms.googleapis.com' - def __init__( - self, *, - host: str = DEFAULT_HOST, - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - """ - - scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} - - # Save the scopes. - self._scopes = scopes - if not hasattr(self, "_ignore_credentials"): - self._ignore_credentials: bool = False - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise core_exceptions.DuplicateCredentialArgs("'credentials_file' and 'credentials' are mutually exclusive") - - if credentials_file is not None: - credentials, _ = google.auth.load_credentials_from_file( - credentials_file, - **scopes_kwargs, - quota_project_id=quota_project_id - ) - elif credentials is None and not self._ignore_credentials: - credentials, _ = google.auth.default(**scopes_kwargs, quota_project_id=quota_project_id) - # Don't apply audience if the credentials file passed from user. - if hasattr(credentials, "with_gdch_audience"): - credentials = credentials.with_gdch_audience(api_audience if api_audience else host) - - # If the credentials are service account credentials, then always try to use self signed JWT. - if always_use_jwt_access and isinstance(credentials, service_account.Credentials) and hasattr(service_account.Credentials, "with_always_use_jwt_access"): - credentials = credentials.with_always_use_jwt_access(True) - - # Save the credentials. - self._credentials = credentials - - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ':' not in host: - host += ':443' - self._host = host - - @property - def host(self): - return self._host - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.list_key_rings: gapic_v1.method.wrap_method( - self.list_key_rings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_crypto_keys: gapic_v1.method.wrap_method( - self.list_crypto_keys, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_crypto_key_versions: gapic_v1.method.wrap_method( - self.list_crypto_key_versions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_import_jobs: gapic_v1.method.wrap_method( - self.list_import_jobs, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_key_ring: gapic_v1.method.wrap_method( - self.get_key_ring, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_crypto_key: gapic_v1.method.wrap_method( - self.get_crypto_key, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_crypto_key_version: gapic_v1.method.wrap_method( - self.get_crypto_key_version, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_public_key: gapic_v1.method.wrap_method( - self.get_public_key, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_import_job: gapic_v1.method.wrap_method( - self.get_import_job, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_key_ring: gapic_v1.method.wrap_method( - self.create_key_ring, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_crypto_key: gapic_v1.method.wrap_method( - self.create_crypto_key, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_crypto_key_version: gapic_v1.method.wrap_method( - self.create_crypto_key_version, - default_timeout=60.0, - client_info=client_info, - ), - self.import_crypto_key_version: gapic_v1.method.wrap_method( - self.import_crypto_key_version, - default_timeout=60.0, - client_info=client_info, - ), - self.create_import_job: gapic_v1.method.wrap_method( - self.create_import_job, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_crypto_key: gapic_v1.method.wrap_method( - self.update_crypto_key, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_crypto_key_version: gapic_v1.method.wrap_method( - self.update_crypto_key_version, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_crypto_key_primary_version: gapic_v1.method.wrap_method( - self.update_crypto_key_primary_version, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.destroy_crypto_key_version: gapic_v1.method.wrap_method( - self.destroy_crypto_key_version, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.restore_crypto_key_version: gapic_v1.method.wrap_method( - self.restore_crypto_key_version, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.encrypt: gapic_v1.method.wrap_method( - self.encrypt, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.decrypt: gapic_v1.method.wrap_method( - self.decrypt, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.raw_encrypt: gapic_v1.method.wrap_method( - self.raw_encrypt, - default_timeout=None, - client_info=client_info, - ), - self.raw_decrypt: gapic_v1.method.wrap_method( - self.raw_decrypt, - default_timeout=None, - client_info=client_info, - ), - self.asymmetric_sign: gapic_v1.method.wrap_method( - self.asymmetric_sign, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.asymmetric_decrypt: gapic_v1.method.wrap_method( - self.asymmetric_decrypt, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.mac_sign: gapic_v1.method.wrap_method( - self.mac_sign, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.mac_verify: gapic_v1.method.wrap_method( - self.mac_verify, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_random_bytes: gapic_v1.method.wrap_method( - self.generate_random_bytes, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_location: gapic_v1.method.wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: gapic_v1.method.wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: gapic_v1.method.wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - } - - 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_key_rings(self) -> Callable[ - [service.ListKeyRingsRequest], - Union[ - service.ListKeyRingsResponse, - Awaitable[service.ListKeyRingsResponse] - ]]: - raise NotImplementedError() - - @property - def list_crypto_keys(self) -> Callable[ - [service.ListCryptoKeysRequest], - Union[ - service.ListCryptoKeysResponse, - Awaitable[service.ListCryptoKeysResponse] - ]]: - raise NotImplementedError() - - @property - def list_crypto_key_versions(self) -> Callable[ - [service.ListCryptoKeyVersionsRequest], - Union[ - service.ListCryptoKeyVersionsResponse, - Awaitable[service.ListCryptoKeyVersionsResponse] - ]]: - raise NotImplementedError() - - @property - def list_import_jobs(self) -> Callable[ - [service.ListImportJobsRequest], - Union[ - service.ListImportJobsResponse, - Awaitable[service.ListImportJobsResponse] - ]]: - raise NotImplementedError() - - @property - def get_key_ring(self) -> Callable[ - [service.GetKeyRingRequest], - Union[ - resources.KeyRing, - Awaitable[resources.KeyRing] - ]]: - raise NotImplementedError() - - @property - def get_crypto_key(self) -> Callable[ - [service.GetCryptoKeyRequest], - Union[ - resources.CryptoKey, - Awaitable[resources.CryptoKey] - ]]: - raise NotImplementedError() - - @property - def get_crypto_key_version(self) -> Callable[ - [service.GetCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def get_public_key(self) -> Callable[ - [service.GetPublicKeyRequest], - Union[ - resources.PublicKey, - Awaitable[resources.PublicKey] - ]]: - raise NotImplementedError() - - @property - def get_import_job(self) -> Callable[ - [service.GetImportJobRequest], - Union[ - resources.ImportJob, - Awaitable[resources.ImportJob] - ]]: - raise NotImplementedError() - - @property - def create_key_ring(self) -> Callable[ - [service.CreateKeyRingRequest], - Union[ - resources.KeyRing, - Awaitable[resources.KeyRing] - ]]: - raise NotImplementedError() - - @property - def create_crypto_key(self) -> Callable[ - [service.CreateCryptoKeyRequest], - Union[ - resources.CryptoKey, - Awaitable[resources.CryptoKey] - ]]: - raise NotImplementedError() - - @property - def create_crypto_key_version(self) -> Callable[ - [service.CreateCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def import_crypto_key_version(self) -> Callable[ - [service.ImportCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def create_import_job(self) -> Callable[ - [service.CreateImportJobRequest], - Union[ - resources.ImportJob, - Awaitable[resources.ImportJob] - ]]: - raise NotImplementedError() - - @property - def update_crypto_key(self) -> Callable[ - [service.UpdateCryptoKeyRequest], - Union[ - resources.CryptoKey, - Awaitable[resources.CryptoKey] - ]]: - raise NotImplementedError() - - @property - def update_crypto_key_version(self) -> Callable[ - [service.UpdateCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def update_crypto_key_primary_version(self) -> Callable[ - [service.UpdateCryptoKeyPrimaryVersionRequest], - Union[ - resources.CryptoKey, - Awaitable[resources.CryptoKey] - ]]: - raise NotImplementedError() - - @property - def destroy_crypto_key_version(self) -> Callable[ - [service.DestroyCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def restore_crypto_key_version(self) -> Callable[ - [service.RestoreCryptoKeyVersionRequest], - Union[ - resources.CryptoKeyVersion, - Awaitable[resources.CryptoKeyVersion] - ]]: - raise NotImplementedError() - - @property - def encrypt(self) -> Callable[ - [service.EncryptRequest], - Union[ - service.EncryptResponse, - Awaitable[service.EncryptResponse] - ]]: - raise NotImplementedError() - - @property - def decrypt(self) -> Callable[ - [service.DecryptRequest], - Union[ - service.DecryptResponse, - Awaitable[service.DecryptResponse] - ]]: - raise NotImplementedError() - - @property - def raw_encrypt(self) -> Callable[ - [service.RawEncryptRequest], - Union[ - service.RawEncryptResponse, - Awaitable[service.RawEncryptResponse] - ]]: - raise NotImplementedError() - - @property - def raw_decrypt(self) -> Callable[ - [service.RawDecryptRequest], - Union[ - service.RawDecryptResponse, - Awaitable[service.RawDecryptResponse] - ]]: - raise NotImplementedError() - - @property - def asymmetric_sign(self) -> Callable[ - [service.AsymmetricSignRequest], - Union[ - service.AsymmetricSignResponse, - Awaitable[service.AsymmetricSignResponse] - ]]: - raise NotImplementedError() - - @property - def asymmetric_decrypt(self) -> Callable[ - [service.AsymmetricDecryptRequest], - Union[ - service.AsymmetricDecryptResponse, - Awaitable[service.AsymmetricDecryptResponse] - ]]: - raise NotImplementedError() - - @property - def mac_sign(self) -> Callable[ - [service.MacSignRequest], - Union[ - service.MacSignResponse, - Awaitable[service.MacSignResponse] - ]]: - raise NotImplementedError() - - @property - def mac_verify(self) -> Callable[ - [service.MacVerifyRequest], - Union[ - service.MacVerifyResponse, - Awaitable[service.MacVerifyResponse] - ]]: - raise NotImplementedError() - - @property - def generate_random_bytes(self) -> Callable[ - [service.GenerateRandomBytesRequest], - Union[ - service.GenerateRandomBytesResponse, - Awaitable[service.GenerateRandomBytesResponse] - ]]: - raise NotImplementedError() - - @property - def get_operation( - self, - ) -> Callable[ - [operations_pb2.GetOperationRequest], - Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], - ]: - raise NotImplementedError() - - @property - def get_location(self, - ) -> Callable[ - [locations_pb2.GetLocationRequest], - Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], - ]: - raise NotImplementedError() - - @property - def list_locations(self, - ) -> Callable[ - [locations_pb2.ListLocationsRequest], - Union[locations_pb2.ListLocationsResponse, Awaitable[locations_pb2.ListLocationsResponse]], - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.SetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> Callable[ - [iam_policy_pb2.GetIamPolicyRequest], - Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Union[ - iam_policy_pb2.TestIamPermissionsResponse, - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def kind(self) -> str: - raise NotImplementedError() - - -__all__ = ( - 'KeyManagementServiceTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py deleted file mode 100644 index e27f19fbadb8..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc.py +++ /dev/null @@ -1,1250 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.kms_v1.types import resources -from google.cloud.kms_v1.types import service -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO - - -class KeyManagementServiceGrpcTransport(KeyManagementServiceTransport): - """gRPC backend transport for KeyManagementService. - - Google Cloud Key Management Service - - Manages cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [KeyRing][google.cloud.kms.v1.KeyRing] - - [CryptoKey][google.cloud.kms.v1.CryptoKey] - - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - - [ImportJob][google.cloud.kms.v1.ImportJob] - - If you are using manual gRPC libraries, see `Using gRPC with Cloud - KMS `__. - - 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 = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if a ``channel`` instance is provided. - channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, grpc.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._prep_wrapped_messages(client_info) - - @classmethod - def create_channel(cls, - host: str = 'cloudkms.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_key_rings(self) -> Callable[ - [service.ListKeyRingsRequest], - service.ListKeyRingsResponse]: - r"""Return a callable for the list key rings method over gRPC. - - Lists [KeyRings][google.cloud.kms.v1.KeyRing]. - - Returns: - Callable[[~.ListKeyRingsRequest], - ~.ListKeyRingsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_key_rings' not in self._stubs: - self._stubs['list_key_rings'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListKeyRings', - request_serializer=service.ListKeyRingsRequest.serialize, - response_deserializer=service.ListKeyRingsResponse.deserialize, - ) - return self._stubs['list_key_rings'] - - @property - def list_crypto_keys(self) -> Callable[ - [service.ListCryptoKeysRequest], - service.ListCryptoKeysResponse]: - r"""Return a callable for the list crypto keys method over gRPC. - - Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.ListCryptoKeysRequest], - ~.ListCryptoKeysResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_keys' not in self._stubs: - self._stubs['list_crypto_keys'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeys', - request_serializer=service.ListCryptoKeysRequest.serialize, - response_deserializer=service.ListCryptoKeysResponse.deserialize, - ) - return self._stubs['list_crypto_keys'] - - @property - def list_crypto_key_versions(self) -> Callable[ - [service.ListCryptoKeyVersionsRequest], - service.ListCryptoKeyVersionsResponse]: - r"""Return a callable for the list crypto key versions method over gRPC. - - Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.ListCryptoKeyVersionsRequest], - ~.ListCryptoKeyVersionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key_versions' not in self._stubs: - self._stubs['list_crypto_key_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeyVersions', - request_serializer=service.ListCryptoKeyVersionsRequest.serialize, - response_deserializer=service.ListCryptoKeyVersionsResponse.deserialize, - ) - return self._stubs['list_crypto_key_versions'] - - @property - def list_import_jobs(self) -> Callable[ - [service.ListImportJobsRequest], - service.ListImportJobsResponse]: - r"""Return a callable for the list import jobs method over gRPC. - - Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. - - Returns: - Callable[[~.ListImportJobsRequest], - ~.ListImportJobsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_import_jobs' not in self._stubs: - self._stubs['list_import_jobs'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListImportJobs', - request_serializer=service.ListImportJobsRequest.serialize, - response_deserializer=service.ListImportJobsResponse.deserialize, - ) - return self._stubs['list_import_jobs'] - - @property - def get_key_ring(self) -> Callable[ - [service.GetKeyRingRequest], - resources.KeyRing]: - r"""Return a callable for the get key ring method over gRPC. - - Returns metadata for a given - [KeyRing][google.cloud.kms.v1.KeyRing]. - - Returns: - Callable[[~.GetKeyRingRequest], - ~.KeyRing]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_key_ring' not in self._stubs: - self._stubs['get_key_ring'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetKeyRing', - request_serializer=service.GetKeyRingRequest.serialize, - response_deserializer=resources.KeyRing.deserialize, - ) - return self._stubs['get_key_ring'] - - @property - def get_crypto_key(self) -> Callable[ - [service.GetCryptoKeyRequest], - resources.CryptoKey]: - r"""Return a callable for the get crypto key method over gRPC. - - Returns metadata for a given - [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its - [primary][google.cloud.kms.v1.CryptoKey.primary] - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.GetCryptoKeyRequest], - ~.CryptoKey]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: - self._stubs['get_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetCryptoKey', - request_serializer=service.GetCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['get_crypto_key'] - - @property - def get_crypto_key_version(self) -> Callable[ - [service.GetCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the get crypto key version method over gRPC. - - Returns metadata for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.GetCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: - self._stubs['get_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetCryptoKeyVersion', - request_serializer=service.GetCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['get_crypto_key_version'] - - @property - def get_public_key(self) -> Callable[ - [service.GetPublicKeyRequest], - resources.PublicKey]: - r"""Return a callable for the get public key method over gRPC. - - Returns the public key for the given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] - or - [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. - - Returns: - Callable[[~.GetPublicKeyRequest], - ~.PublicKey]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_public_key' not in self._stubs: - self._stubs['get_public_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetPublicKey', - request_serializer=service.GetPublicKeyRequest.serialize, - response_deserializer=resources.PublicKey.deserialize, - ) - return self._stubs['get_public_key'] - - @property - def get_import_job(self) -> Callable[ - [service.GetImportJobRequest], - resources.ImportJob]: - r"""Return a callable for the get import job method over gRPC. - - Returns metadata for a given - [ImportJob][google.cloud.kms.v1.ImportJob]. - - Returns: - Callable[[~.GetImportJobRequest], - ~.ImportJob]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_import_job' not in self._stubs: - self._stubs['get_import_job'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetImportJob', - request_serializer=service.GetImportJobRequest.serialize, - response_deserializer=resources.ImportJob.deserialize, - ) - return self._stubs['get_import_job'] - - @property - def create_key_ring(self) -> Callable[ - [service.CreateKeyRingRequest], - resources.KeyRing]: - r"""Return a callable for the create key ring method over gRPC. - - Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given - Project and Location. - - Returns: - Callable[[~.CreateKeyRingRequest], - ~.KeyRing]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_key_ring' not in self._stubs: - self._stubs['create_key_ring'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateKeyRing', - request_serializer=service.CreateKeyRingRequest.serialize, - response_deserializer=resources.KeyRing.deserialize, - ) - return self._stubs['create_key_ring'] - - @property - def create_crypto_key(self) -> Callable[ - [service.CreateCryptoKeyRequest], - resources.CryptoKey]: - r"""Return a callable for the create crypto key method over gRPC. - - Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and - [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] - are required. - - Returns: - Callable[[~.CreateCryptoKeyRequest], - ~.CryptoKey]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: - self._stubs['create_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKey', - request_serializer=service.CreateCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['create_crypto_key'] - - @property - def create_crypto_key_version(self) -> Callable[ - [service.CreateCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the create crypto key version method over gRPC. - - Create a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - The server will assign the next sequential id. If unset, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. - - Returns: - Callable[[~.CreateCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: - self._stubs['create_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKeyVersion', - request_serializer=service.CreateCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['create_crypto_key_version'] - - @property - def import_crypto_key_version(self) -> Callable[ - [service.ImportCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the import crypto key version method over gRPC. - - Import wrapped key material into a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - All requests must specify a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is - additionally specified in the request, key material will be - reimported into that version. Otherwise, a new version will be - created, and will be assigned the next sequential id within the - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.ImportCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_crypto_key_version' not in self._stubs: - self._stubs['import_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ImportCryptoKeyVersion', - request_serializer=service.ImportCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['import_crypto_key_version'] - - @property - def create_import_job(self) -> Callable[ - [service.CreateImportJobRequest], - resources.ImportJob]: - r"""Return a callable for the create import job method over gRPC. - - Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] - is required. - - Returns: - Callable[[~.CreateImportJobRequest], - ~.ImportJob]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_import_job' not in self._stubs: - self._stubs['create_import_job'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateImportJob', - request_serializer=service.CreateImportJobRequest.serialize, - response_deserializer=resources.ImportJob.deserialize, - ) - return self._stubs['create_import_job'] - - @property - def update_crypto_key(self) -> Callable[ - [service.UpdateCryptoKeyRequest], - resources.CryptoKey]: - r"""Return a callable for the update crypto key method over gRPC. - - Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.UpdateCryptoKeyRequest], - ~.CryptoKey]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: - self._stubs['update_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKey', - request_serializer=service.UpdateCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['update_crypto_key'] - - @property - def update_crypto_key_version(self) -> Callable[ - [service.UpdateCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the update crypto key version method over gRPC. - - Update a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - metadata. - - [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be - changed between - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - and - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] - using this method. See - [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] - and - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - to move between other states. - - Returns: - Callable[[~.UpdateCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: - self._stubs['update_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyVersion', - request_serializer=service.UpdateCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['update_crypto_key_version'] - - @property - def update_crypto_key_primary_version(self) -> Callable[ - [service.UpdateCryptoKeyPrimaryVersionRequest], - resources.CryptoKey]: - r"""Return a callable for the update crypto key primary - version method over gRPC. - - Update the version of a - [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Returns an error if called on a key whose purpose is not - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.UpdateCryptoKeyPrimaryVersionRequest], - ~.CryptoKey]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key_primary_version' not in self._stubs: - self._stubs['update_crypto_key_primary_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyPrimaryVersion', - request_serializer=service.UpdateCryptoKeyPrimaryVersionRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['update_crypto_key_primary_version'] - - @property - def destroy_crypto_key_version(self) -> Callable[ - [service.DestroyCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the destroy crypto key version method over gRPC. - - Schedule a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for - destruction. - - Upon calling this method, - [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] - will be set to - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be set to the time - [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] - in the future. At that time, the - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will - automatically change to - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], - and the key material will be irrevocably destroyed. - - Before the - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - is reached, - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - may be called to reverse the process. - - Returns: - Callable[[~.DestroyCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'destroy_crypto_key_version' not in self._stubs: - self._stubs['destroy_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/DestroyCryptoKeyVersion', - request_serializer=service.DestroyCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['destroy_crypto_key_version'] - - @property - def restore_crypto_key_version(self) -> Callable[ - [service.RestoreCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - r"""Return a callable for the restore crypto key version method over gRPC. - - Restore a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] - state. - - Upon restoration of the CryptoKeyVersion, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be cleared. - - Returns: - Callable[[~.RestoreCryptoKeyVersionRequest], - ~.CryptoKeyVersion]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'restore_crypto_key_version' not in self._stubs: - self._stubs['restore_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/RestoreCryptoKeyVersion', - request_serializer=service.RestoreCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['restore_crypto_key_version'] - - @property - def encrypt(self) -> Callable[ - [service.EncryptRequest], - service.EncryptResponse]: - r"""Return a callable for the encrypt method over gRPC. - - Encrypts data, so that it can only be recovered by a call to - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.EncryptRequest], - ~.EncryptResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'encrypt' not in self._stubs: - self._stubs['encrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/Encrypt', - request_serializer=service.EncryptRequest.serialize, - response_deserializer=service.EncryptResponse.deserialize, - ) - return self._stubs['encrypt'] - - @property - def decrypt(self) -> Callable[ - [service.DecryptRequest], - service.DecryptResponse]: - r"""Return a callable for the decrypt method over gRPC. - - Decrypts data that was protected by - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.DecryptRequest], - ~.DecryptResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'decrypt' not in self._stubs: - self._stubs['decrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/Decrypt', - request_serializer=service.DecryptRequest.serialize, - response_deserializer=service.DecryptResponse.deserialize, - ) - return self._stubs['decrypt'] - - @property - def raw_encrypt(self) -> Callable[ - [service.RawEncryptRequest], - service.RawEncryptResponse]: - r"""Return a callable for the raw encrypt method over gRPC. - - Encrypts data using portable cryptographic primitives. Most - users should choose - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] and - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt] - rather than their raw counterparts. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.RawEncryptRequest], - ~.RawEncryptResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'raw_encrypt' not in self._stubs: - self._stubs['raw_encrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/RawEncrypt', - request_serializer=service.RawEncryptRequest.serialize, - response_deserializer=service.RawEncryptResponse.deserialize, - ) - return self._stubs['raw_encrypt'] - - @property - def raw_decrypt(self) -> Callable[ - [service.RawDecryptRequest], - service.RawDecryptResponse]: - r"""Return a callable for the raw decrypt method over gRPC. - - Decrypts data that was originally encrypted using a raw - cryptographic mechanism. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.RawDecryptRequest], - ~.RawDecryptResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'raw_decrypt' not in self._stubs: - self._stubs['raw_decrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/RawDecrypt', - request_serializer=service.RawDecryptRequest.serialize, - response_deserializer=service.RawDecryptResponse.deserialize, - ) - return self._stubs['raw_decrypt'] - - @property - def asymmetric_sign(self) -> Callable[ - [service.AsymmetricSignRequest], - service.AsymmetricSignResponse]: - r"""Return a callable for the asymmetric sign method over gRPC. - - Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_SIGN, producing a signature that can be verified with - the public key retrieved from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - Returns: - Callable[[~.AsymmetricSignRequest], - ~.AsymmetricSignResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'asymmetric_sign' not in self._stubs: - self._stubs['asymmetric_sign'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/AsymmetricSign', - request_serializer=service.AsymmetricSignRequest.serialize, - response_deserializer=service.AsymmetricSignResponse.deserialize, - ) - return self._stubs['asymmetric_sign'] - - @property - def asymmetric_decrypt(self) -> Callable[ - [service.AsymmetricDecryptRequest], - service.AsymmetricDecryptResponse]: - r"""Return a callable for the asymmetric decrypt method over gRPC. - - Decrypts data that was encrypted with a public key retrieved - from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] - corresponding to a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_DECRYPT. - - Returns: - Callable[[~.AsymmetricDecryptRequest], - ~.AsymmetricDecryptResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'asymmetric_decrypt' not in self._stubs: - self._stubs['asymmetric_decrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/AsymmetricDecrypt', - request_serializer=service.AsymmetricDecryptRequest.serialize, - response_deserializer=service.AsymmetricDecryptResponse.deserialize, - ) - return self._stubs['asymmetric_decrypt'] - - @property - def mac_sign(self) -> Callable[ - [service.MacSignRequest], - service.MacSignResponse]: - r"""Return a callable for the mac sign method over gRPC. - - Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - producing a tag that can be verified by another source with the - same key. - - Returns: - Callable[[~.MacSignRequest], - ~.MacSignResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'mac_sign' not in self._stubs: - self._stubs['mac_sign'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/MacSign', - request_serializer=service.MacSignRequest.serialize, - response_deserializer=service.MacSignResponse.deserialize, - ) - return self._stubs['mac_sign'] - - @property - def mac_verify(self) -> Callable[ - [service.MacVerifyRequest], - service.MacVerifyResponse]: - r"""Return a callable for the mac verify method over gRPC. - - Verifies MAC tag using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - and returns a response that indicates whether or not the - verification was successful. - - Returns: - Callable[[~.MacVerifyRequest], - ~.MacVerifyResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'mac_verify' not in self._stubs: - self._stubs['mac_verify'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/MacVerify', - request_serializer=service.MacVerifyRequest.serialize, - response_deserializer=service.MacVerifyResponse.deserialize, - ) - return self._stubs['mac_verify'] - - @property - def generate_random_bytes(self) -> Callable[ - [service.GenerateRandomBytesRequest], - service.GenerateRandomBytesResponse]: - r"""Return a callable for the generate random bytes method over gRPC. - - Generate random bytes using the Cloud KMS randomness - source in the provided location. - - Returns: - Callable[[~.GenerateRandomBytesRequest], - ~.GenerateRandomBytesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_random_bytes' not in self._stubs: - self._stubs['generate_random_bytes'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GenerateRandomBytes', - request_serializer=service.GenerateRandomBytesRequest.serialize, - response_deserializer=service.GenerateRandomBytesResponse.deserialize, - ) - return self._stubs['generate_random_bytes'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], iam_policy_pb2.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - def close(self): - self.grpc_channel.close() - - @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_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - @property - def kind(self) -> str: - return "grpc" - - -__all__ = ( - 'KeyManagementServiceGrpcTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py deleted file mode 100644 index dc7465ff0077..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,1677 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import inspect -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union - -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers_async -from google.api_core import exceptions as core_exceptions -from google.api_core import retry_async as retries -from google.auth import credentials as ga_credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.kms_v1.types import resources -from google.cloud.kms_v1.types import service -from google.cloud.location import locations_pb2 # type: ignore -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from .base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import KeyManagementServiceGrpcTransport - - -class KeyManagementServiceGrpcAsyncIOTransport(KeyManagementServiceTransport): - """gRPC AsyncIO backend transport for KeyManagementService. - - Google Cloud Key Management Service - - Manages cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [KeyRing][google.cloud.kms.v1.KeyRing] - - [CryptoKey][google.cloud.kms.v1.CryptoKey] - - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - - [ImportJob][google.cloud.kms.v1.ImportJob] - - If you are using manual gRPC libraries, see `Using gRPC with Cloud - KMS `__. - - 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 = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - host (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - quota_project_id=quota_project_id, - default_scopes=cls.AUTH_SCOPES, - scopes=scopes, - default_host=cls.DEFAULT_HOST, - **kwargs - ) - - def __init__(self, *, - host: str = 'cloudkms.googleapis.com', - credentials: Optional[ga_credentials.Credentials] = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, - api_mtls_endpoint: Optional[str] = None, - client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, - client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if a ``channel`` instance is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if a ``channel`` instance is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): - A ``Channel`` instance through which to make calls, or a Callable - that constructs and returns one. If set to None, ``self.create_channel`` - is used to create the channel. If a Callable is given, it will be called - with the same arguments as used in ``self.create_channel``. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or application default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if a ``channel`` instance is provided. - client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): - A callback to provide client certificate bytes and private key bytes, - both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._grpc_channel = None - self._ssl_channel_credentials = ssl_channel_credentials - self._stubs: Dict[str, Callable] = {} - - if api_mtls_endpoint: - warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) - if client_cert_source: - warnings.warn("client_cert_source is deprecated", DeprecationWarning) - - if isinstance(channel, aio.Channel): - # Ignore credentials if a channel was passed. - credentials = None - self._ignore_credentials = True - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - else: - if api_mtls_endpoint: - host = api_mtls_endpoint - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - self._ssl_channel_credentials = SslCredentials().ssl_credentials - - else: - if client_cert_source_for_mtls and not ssl_channel_credentials: - cert, key = client_cert_source_for_mtls() - self._ssl_channel_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - - # The base transport sets the host, credentials and scopes - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience, - ) - - if not self._grpc_channel: - # initialize with the provided callable or the default channel - channel_init = channel or type(self).create_channel - self._grpc_channel = channel_init( - self._host, - # use the credentials which are saved - credentials=self._credentials, - # Set ``credentials_file`` to ``None`` here as - # the credentials that we saved earlier should be used. - credentials_file=None, - scopes=self._scopes, - ssl_credentials=self._ssl_channel_credentials, - quota_project_id=quota_project_id, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Wrap messages. This must be done after self._grpc_channel exists - self._wrap_with_kind = "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters - 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_key_rings(self) -> Callable[ - [service.ListKeyRingsRequest], - Awaitable[service.ListKeyRingsResponse]]: - r"""Return a callable for the list key rings method over gRPC. - - Lists [KeyRings][google.cloud.kms.v1.KeyRing]. - - Returns: - Callable[[~.ListKeyRingsRequest], - Awaitable[~.ListKeyRingsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_key_rings' not in self._stubs: - self._stubs['list_key_rings'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListKeyRings', - request_serializer=service.ListKeyRingsRequest.serialize, - response_deserializer=service.ListKeyRingsResponse.deserialize, - ) - return self._stubs['list_key_rings'] - - @property - def list_crypto_keys(self) -> Callable[ - [service.ListCryptoKeysRequest], - Awaitable[service.ListCryptoKeysResponse]]: - r"""Return a callable for the list crypto keys method over gRPC. - - Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.ListCryptoKeysRequest], - Awaitable[~.ListCryptoKeysResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_keys' not in self._stubs: - self._stubs['list_crypto_keys'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeys', - request_serializer=service.ListCryptoKeysRequest.serialize, - response_deserializer=service.ListCryptoKeysResponse.deserialize, - ) - return self._stubs['list_crypto_keys'] - - @property - def list_crypto_key_versions(self) -> Callable[ - [service.ListCryptoKeyVersionsRequest], - Awaitable[service.ListCryptoKeyVersionsResponse]]: - r"""Return a callable for the list crypto key versions method over gRPC. - - Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.ListCryptoKeyVersionsRequest], - Awaitable[~.ListCryptoKeyVersionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key_versions' not in self._stubs: - self._stubs['list_crypto_key_versions'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListCryptoKeyVersions', - request_serializer=service.ListCryptoKeyVersionsRequest.serialize, - response_deserializer=service.ListCryptoKeyVersionsResponse.deserialize, - ) - return self._stubs['list_crypto_key_versions'] - - @property - def list_import_jobs(self) -> Callable[ - [service.ListImportJobsRequest], - Awaitable[service.ListImportJobsResponse]]: - r"""Return a callable for the list import jobs method over gRPC. - - Lists [ImportJobs][google.cloud.kms.v1.ImportJob]. - - Returns: - Callable[[~.ListImportJobsRequest], - Awaitable[~.ListImportJobsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_import_jobs' not in self._stubs: - self._stubs['list_import_jobs'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ListImportJobs', - request_serializer=service.ListImportJobsRequest.serialize, - response_deserializer=service.ListImportJobsResponse.deserialize, - ) - return self._stubs['list_import_jobs'] - - @property - def get_key_ring(self) -> Callable[ - [service.GetKeyRingRequest], - Awaitable[resources.KeyRing]]: - r"""Return a callable for the get key ring method over gRPC. - - Returns metadata for a given - [KeyRing][google.cloud.kms.v1.KeyRing]. - - Returns: - Callable[[~.GetKeyRingRequest], - Awaitable[~.KeyRing]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_key_ring' not in self._stubs: - self._stubs['get_key_ring'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetKeyRing', - request_serializer=service.GetKeyRingRequest.serialize, - response_deserializer=resources.KeyRing.deserialize, - ) - return self._stubs['get_key_ring'] - - @property - def get_crypto_key(self) -> Callable[ - [service.GetCryptoKeyRequest], - Awaitable[resources.CryptoKey]]: - r"""Return a callable for the get crypto key method over gRPC. - - Returns metadata for a given - [CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its - [primary][google.cloud.kms.v1.CryptoKey.primary] - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.GetCryptoKeyRequest], - Awaitable[~.CryptoKey]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: - self._stubs['get_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetCryptoKey', - request_serializer=service.GetCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['get_crypto_key'] - - @property - def get_crypto_key_version(self) -> Callable[ - [service.GetCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the get crypto key version method over gRPC. - - Returns metadata for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Returns: - Callable[[~.GetCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: - self._stubs['get_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetCryptoKeyVersion', - request_serializer=service.GetCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['get_crypto_key_version'] - - @property - def get_public_key(self) -> Callable[ - [service.GetPublicKeyRequest], - Awaitable[resources.PublicKey]]: - r"""Return a callable for the get public key method over gRPC. - - Returns the public key for the given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN] - or - [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. - - Returns: - Callable[[~.GetPublicKeyRequest], - Awaitable[~.PublicKey]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_public_key' not in self._stubs: - self._stubs['get_public_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetPublicKey', - request_serializer=service.GetPublicKeyRequest.serialize, - response_deserializer=resources.PublicKey.deserialize, - ) - return self._stubs['get_public_key'] - - @property - def get_import_job(self) -> Callable[ - [service.GetImportJobRequest], - Awaitable[resources.ImportJob]]: - r"""Return a callable for the get import job method over gRPC. - - Returns metadata for a given - [ImportJob][google.cloud.kms.v1.ImportJob]. - - Returns: - Callable[[~.GetImportJobRequest], - Awaitable[~.ImportJob]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_import_job' not in self._stubs: - self._stubs['get_import_job'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GetImportJob', - request_serializer=service.GetImportJobRequest.serialize, - response_deserializer=resources.ImportJob.deserialize, - ) - return self._stubs['get_import_job'] - - @property - def create_key_ring(self) -> Callable[ - [service.CreateKeyRingRequest], - Awaitable[resources.KeyRing]]: - r"""Return a callable for the create key ring method over gRPC. - - Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given - Project and Location. - - Returns: - Callable[[~.CreateKeyRingRequest], - Awaitable[~.KeyRing]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_key_ring' not in self._stubs: - self._stubs['create_key_ring'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateKeyRing', - request_serializer=service.CreateKeyRingRequest.serialize, - response_deserializer=resources.KeyRing.deserialize, - ) - return self._stubs['create_key_ring'] - - @property - def create_crypto_key(self) -> Callable[ - [service.CreateCryptoKeyRequest], - Awaitable[resources.CryptoKey]]: - r"""Return a callable for the create crypto key method over gRPC. - - Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and - [CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm] - are required. - - Returns: - Callable[[~.CreateCryptoKeyRequest], - Awaitable[~.CryptoKey]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: - self._stubs['create_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKey', - request_serializer=service.CreateCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['create_crypto_key'] - - @property - def create_crypto_key_version(self) -> Callable[ - [service.CreateCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the create crypto key version method over gRPC. - - Create a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - The server will assign the next sequential id. If unset, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]. - - Returns: - Callable[[~.CreateCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: - self._stubs['create_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateCryptoKeyVersion', - request_serializer=service.CreateCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['create_crypto_key_version'] - - @property - def import_crypto_key_version(self) -> Callable[ - [service.ImportCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the import crypto key version method over gRPC. - - Import wrapped key material into a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - All requests must specify a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is - additionally specified in the request, key material will be - reimported into that version. Otherwise, a new version will be - created, and will be assigned the next sequential id within the - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.ImportCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'import_crypto_key_version' not in self._stubs: - self._stubs['import_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/ImportCryptoKeyVersion', - request_serializer=service.ImportCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['import_crypto_key_version'] - - @property - def create_import_job(self) -> Callable[ - [service.CreateImportJobRequest], - Awaitable[resources.ImportJob]]: - r"""Return a callable for the create import job method over gRPC. - - Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a - [KeyRing][google.cloud.kms.v1.KeyRing]. - - [ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method] - is required. - - Returns: - Callable[[~.CreateImportJobRequest], - Awaitable[~.ImportJob]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_import_job' not in self._stubs: - self._stubs['create_import_job'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/CreateImportJob', - request_serializer=service.CreateImportJobRequest.serialize, - response_deserializer=resources.ImportJob.deserialize, - ) - return self._stubs['create_import_job'] - - @property - def update_crypto_key(self) -> Callable[ - [service.UpdateCryptoKeyRequest], - Awaitable[resources.CryptoKey]]: - r"""Return a callable for the update crypto key method over gRPC. - - Update a [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Returns: - Callable[[~.UpdateCryptoKeyRequest], - Awaitable[~.CryptoKey]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key' not in self._stubs: - self._stubs['update_crypto_key'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKey', - request_serializer=service.UpdateCryptoKeyRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['update_crypto_key'] - - @property - def update_crypto_key_version(self) -> Callable[ - [service.UpdateCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the update crypto key version method over gRPC. - - Update a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - metadata. - - [state][google.cloud.kms.v1.CryptoKeyVersion.state] may be - changed between - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - and - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] - using this method. See - [DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion] - and - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - to move between other states. - - Returns: - Callable[[~.UpdateCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key_version' not in self._stubs: - self._stubs['update_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyVersion', - request_serializer=service.UpdateCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['update_crypto_key_version'] - - @property - def update_crypto_key_primary_version(self) -> Callable[ - [service.UpdateCryptoKeyPrimaryVersionRequest], - Awaitable[resources.CryptoKey]]: - r"""Return a callable for the update crypto key primary - version method over gRPC. - - Update the version of a - [CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Returns an error if called on a key whose purpose is not - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.UpdateCryptoKeyPrimaryVersionRequest], - Awaitable[~.CryptoKey]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-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_crypto_key_primary_version' not in self._stubs: - self._stubs['update_crypto_key_primary_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyPrimaryVersion', - request_serializer=service.UpdateCryptoKeyPrimaryVersionRequest.serialize, - response_deserializer=resources.CryptoKey.deserialize, - ) - return self._stubs['update_crypto_key_primary_version'] - - @property - def destroy_crypto_key_version(self) -> Callable[ - [service.DestroyCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the destroy crypto key version method over gRPC. - - Schedule a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for - destruction. - - Upon calling this method, - [CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state] - will be set to - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be set to the time - [destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration] - in the future. At that time, the - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will - automatically change to - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED], - and the key material will be irrevocably destroyed. - - Before the - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - is reached, - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - may be called to reverse the process. - - Returns: - Callable[[~.DestroyCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'destroy_crypto_key_version' not in self._stubs: - self._stubs['destroy_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/DestroyCryptoKeyVersion', - request_serializer=service.DestroyCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['destroy_crypto_key_version'] - - @property - def restore_crypto_key_version(self) -> Callable[ - [service.RestoreCryptoKeyVersionRequest], - Awaitable[resources.CryptoKeyVersion]]: - r"""Return a callable for the restore crypto key version method over gRPC. - - Restore a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] - state. - - Upon restoration of the CryptoKeyVersion, - [state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set - to - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED], - and - [destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time] - will be cleared. - - Returns: - Callable[[~.RestoreCryptoKeyVersionRequest], - Awaitable[~.CryptoKeyVersion]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'restore_crypto_key_version' not in self._stubs: - self._stubs['restore_crypto_key_version'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/RestoreCryptoKeyVersion', - request_serializer=service.RestoreCryptoKeyVersionRequest.serialize, - response_deserializer=resources.CryptoKeyVersion.deserialize, - ) - return self._stubs['restore_crypto_key_version'] - - @property - def encrypt(self) -> Callable[ - [service.EncryptRequest], - Awaitable[service.EncryptResponse]]: - r"""Return a callable for the encrypt method over gRPC. - - Encrypts data, so that it can only be recovered by a call to - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.EncryptRequest], - Awaitable[~.EncryptResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'encrypt' not in self._stubs: - self._stubs['encrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/Encrypt', - request_serializer=service.EncryptRequest.serialize, - response_deserializer=service.EncryptResponse.deserialize, - ) - return self._stubs['encrypt'] - - @property - def decrypt(self) -> Callable[ - [service.DecryptRequest], - Awaitable[service.DecryptResponse]]: - r"""Return a callable for the decrypt method over gRPC. - - Decrypts data that was protected by - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.DecryptRequest], - Awaitable[~.DecryptResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'decrypt' not in self._stubs: - self._stubs['decrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/Decrypt', - request_serializer=service.DecryptRequest.serialize, - response_deserializer=service.DecryptResponse.deserialize, - ) - return self._stubs['decrypt'] - - @property - def raw_encrypt(self) -> Callable[ - [service.RawEncryptRequest], - Awaitable[service.RawEncryptResponse]]: - r"""Return a callable for the raw encrypt method over gRPC. - - Encrypts data using portable cryptographic primitives. Most - users should choose - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] and - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt] - rather than their raw counterparts. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.RawEncryptRequest], - Awaitable[~.RawEncryptResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'raw_encrypt' not in self._stubs: - self._stubs['raw_encrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/RawEncrypt', - request_serializer=service.RawEncryptRequest.serialize, - response_deserializer=service.RawEncryptResponse.deserialize, - ) - return self._stubs['raw_encrypt'] - - @property - def raw_decrypt(self) -> Callable[ - [service.RawDecryptRequest], - Awaitable[service.RawDecryptResponse]]: - r"""Return a callable for the raw decrypt method over gRPC. - - Decrypts data that was originally encrypted using a raw - cryptographic mechanism. The - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must - be - [RAW_ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.RAW_ENCRYPT_DECRYPT]. - - Returns: - Callable[[~.RawDecryptRequest], - Awaitable[~.RawDecryptResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'raw_decrypt' not in self._stubs: - self._stubs['raw_decrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/RawDecrypt', - request_serializer=service.RawDecryptRequest.serialize, - response_deserializer=service.RawDecryptResponse.deserialize, - ) - return self._stubs['raw_decrypt'] - - @property - def asymmetric_sign(self) -> Callable[ - [service.AsymmetricSignRequest], - Awaitable[service.AsymmetricSignResponse]]: - r"""Return a callable for the asymmetric sign method over gRPC. - - Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_SIGN, producing a signature that can be verified with - the public key retrieved from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - Returns: - Callable[[~.AsymmetricSignRequest], - Awaitable[~.AsymmetricSignResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'asymmetric_sign' not in self._stubs: - self._stubs['asymmetric_sign'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/AsymmetricSign', - request_serializer=service.AsymmetricSignRequest.serialize, - response_deserializer=service.AsymmetricSignResponse.deserialize, - ) - return self._stubs['asymmetric_sign'] - - @property - def asymmetric_decrypt(self) -> Callable[ - [service.AsymmetricDecryptRequest], - Awaitable[service.AsymmetricDecryptResponse]]: - r"""Return a callable for the asymmetric decrypt method over gRPC. - - Decrypts data that was encrypted with a public key retrieved - from - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] - corresponding to a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - ASYMMETRIC_DECRYPT. - - Returns: - Callable[[~.AsymmetricDecryptRequest], - Awaitable[~.AsymmetricDecryptResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'asymmetric_decrypt' not in self._stubs: - self._stubs['asymmetric_decrypt'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/AsymmetricDecrypt', - request_serializer=service.AsymmetricDecryptRequest.serialize, - response_deserializer=service.AsymmetricDecryptResponse.deserialize, - ) - return self._stubs['asymmetric_decrypt'] - - @property - def mac_sign(self) -> Callable[ - [service.MacSignRequest], - Awaitable[service.MacSignResponse]]: - r"""Return a callable for the mac sign method over gRPC. - - Signs data using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - producing a tag that can be verified by another source with the - same key. - - Returns: - Callable[[~.MacSignRequest], - Awaitable[~.MacSignResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'mac_sign' not in self._stubs: - self._stubs['mac_sign'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/MacSign', - request_serializer=service.MacSignRequest.serialize, - response_deserializer=service.MacSignResponse.deserialize, - ) - return self._stubs['mac_sign'] - - @property - def mac_verify(self) -> Callable[ - [service.MacVerifyRequest], - Awaitable[service.MacVerifyResponse]]: - r"""Return a callable for the mac verify method over gRPC. - - Verifies MAC tag using a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC, - and returns a response that indicates whether or not the - verification was successful. - - Returns: - Callable[[~.MacVerifyRequest], - Awaitable[~.MacVerifyResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'mac_verify' not in self._stubs: - self._stubs['mac_verify'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/MacVerify', - request_serializer=service.MacVerifyRequest.serialize, - response_deserializer=service.MacVerifyResponse.deserialize, - ) - return self._stubs['mac_verify'] - - @property - def generate_random_bytes(self) -> Callable[ - [service.GenerateRandomBytesRequest], - Awaitable[service.GenerateRandomBytesResponse]]: - r"""Return a callable for the generate random bytes method over gRPC. - - Generate random bytes using the Cloud KMS randomness - source in the provided location. - - Returns: - Callable[[~.GenerateRandomBytesRequest], - Awaitable[~.GenerateRandomBytesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if 'generate_random_bytes' not in self._stubs: - self._stubs['generate_random_bytes'] = self.grpc_channel.unary_unary( - '/google.cloud.kms.v1.KeyManagementService/GenerateRandomBytes', - request_serializer=service.GenerateRandomBytesRequest.serialize, - response_deserializer=service.GenerateRandomBytesResponse.deserialize, - ) - return self._stubs['generate_random_bytes'] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - Sets the IAM access control policy on the specified - function. Replaces any existing policy. - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/SetIamPolicy", - request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - Gets the IAM access control policy for a function. - Returns an empty policy if the function exists and does - not have a policy set. - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/GetIamPolicy", - request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy_pb2.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy_pb2.TestIamPermissionsRequest], - Awaitable[iam_policy_pb2.TestIamPermissionsResponse], - ]: - r"""Return a callable for the test iam permissions method over gRPC. - Tests the specified permissions against the IAM access control - policy for a function. If the function does not exist, this will - return an empty set of permissions, not a NOT_FOUND error. - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.iam.v1.IAMPolicy/TestIamPermissions", - request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - def _prep_wrapped_messages(self, client_info): - """ Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_key_rings: self._wrap_method( - self.list_key_rings, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_crypto_keys: self._wrap_method( - self.list_crypto_keys, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_crypto_key_versions: self._wrap_method( - self.list_crypto_key_versions, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_import_jobs: self._wrap_method( - self.list_import_jobs, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_key_ring: self._wrap_method( - self.get_key_ring, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_crypto_key: self._wrap_method( - self.get_crypto_key, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_crypto_key_version: self._wrap_method( - self.get_crypto_key_version, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_public_key: self._wrap_method( - self.get_public_key, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_import_job: self._wrap_method( - self.get_import_job, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_key_ring: self._wrap_method( - self.create_key_ring, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_crypto_key: self._wrap_method( - self.create_crypto_key, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_crypto_key_version: self._wrap_method( - self.create_crypto_key_version, - default_timeout=60.0, - client_info=client_info, - ), - self.import_crypto_key_version: self._wrap_method( - self.import_crypto_key_version, - default_timeout=60.0, - client_info=client_info, - ), - self.create_import_job: self._wrap_method( - self.create_import_job, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_crypto_key: self._wrap_method( - self.update_crypto_key, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_crypto_key_version: self._wrap_method( - self.update_crypto_key_version, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_crypto_key_primary_version: self._wrap_method( - self.update_crypto_key_primary_version, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.destroy_crypto_key_version: self._wrap_method( - self.destroy_crypto_key_version, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.restore_crypto_key_version: self._wrap_method( - self.restore_crypto_key_version, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.encrypt: self._wrap_method( - self.encrypt, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.decrypt: self._wrap_method( - self.decrypt, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.raw_encrypt: self._wrap_method( - self.raw_encrypt, - default_timeout=None, - client_info=client_info, - ), - self.raw_decrypt: self._wrap_method( - self.raw_decrypt, - default_timeout=None, - client_info=client_info, - ), - self.asymmetric_sign: self._wrap_method( - self.asymmetric_sign, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.asymmetric_decrypt: self._wrap_method( - self.asymmetric_decrypt, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.mac_sign: self._wrap_method( - self.mac_sign, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.mac_verify: self._wrap_method( - self.mac_verify, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.generate_random_bytes: self._wrap_method( - self.generate_random_bytes, - default_retry=retries.AsyncRetry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.DeadlineExceeded, - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_location: self._wrap_method( - self.get_location, - default_timeout=None, - client_info=client_info, - ), - self.list_locations: self._wrap_method( - self.list_locations, - default_timeout=None, - client_info=client_info, - ), - self.get_iam_policy: self._wrap_method( - self.get_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.set_iam_policy: self._wrap_method( - self.set_iam_policy, - default_timeout=None, - client_info=client_info, - ), - self.test_iam_permissions: self._wrap_method( - self.test_iam_permissions, - default_timeout=None, - client_info=client_info, - ), - self.get_operation: self._wrap_method( - self.get_operation, - default_timeout=None, - client_info=client_info, - ), - } - - def _wrap_method(self, func, *args, **kwargs): - if self._wrap_with_kind: # pragma: NO COVER - kwargs["kind"] = self.kind - return gapic_v1.method_async.wrap_method(func, *args, **kwargs) - - def close(self): - return self.grpc_channel.close() - - @property - def kind(self) -> str: - return "grpc_asyncio" - - @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_locations( - self, - ) -> Callable[[locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "list_locations" not in self._stubs: - self._stubs["list_locations"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/ListLocations", - request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, - response_deserializer=locations_pb2.ListLocationsResponse.FromString, - ) - return self._stubs["list_locations"] - - @property - def get_location( - self, - ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: - r"""Return a callable for the list locations method over gRPC. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "get_location" not in self._stubs: - self._stubs["get_location"] = self.grpc_channel.unary_unary( - "/google.cloud.location.Locations/GetLocation", - request_serializer=locations_pb2.GetLocationRequest.SerializeToString, - response_deserializer=locations_pb2.Location.FromString, - ) - return self._stubs["get_location"] - - -__all__ = ( - 'KeyManagementServiceGrpcAsyncIOTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest.py deleted file mode 100644 index 52f7bfa80310..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest.py +++ /dev/null @@ -1,4008 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 -from google.auth import credentials as ga_credentials # type: ignore -from google.api_core import exceptions as core_exceptions -from google.api_core import retry as retries -from google.api_core import rest_helpers -from google.api_core import rest_streaming -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore - -from requests import __version__ as requests_version -import dataclasses -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union -import warnings - - -from google.cloud.kms_v1.types import resources -from google.cloud.kms_v1.types import service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -from .rest_base import _BaseKeyManagementServiceRestTransport -from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO - -try: - OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] -except AttributeError: # pragma: NO COVER - OptionalRetry = Union[retries.Retry, object, None] # type: ignore - - -DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, - grpc_version=None, - rest_version=f"requests@{requests_version}", -) - - -class KeyManagementServiceRestInterceptor: - """Interceptor for KeyManagementService. - - 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 KeyManagementServiceRestTransport. - - .. code-block:: python - class MyCustomKeyManagementServiceInterceptor(KeyManagementServiceRestInterceptor): - def pre_asymmetric_decrypt(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_asymmetric_decrypt(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_asymmetric_sign(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_asymmetric_sign(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_crypto_key(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_crypto_key(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_crypto_key_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_crypto_key_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_import_job(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_import_job(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_create_key_ring(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_create_key_ring(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_decrypt(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_decrypt(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_destroy_crypto_key_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_destroy_crypto_key_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_encrypt(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_encrypt(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_generate_random_bytes(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_generate_random_bytes(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_crypto_key(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_crypto_key(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_crypto_key_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_crypto_key_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_import_job(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_import_job(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_key_ring(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_key_ring(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_get_public_key(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_get_public_key(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_import_crypto_key_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_import_crypto_key_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_crypto_keys(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_crypto_keys(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_crypto_key_versions(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_crypto_key_versions(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_import_jobs(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_import_jobs(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_list_key_rings(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_list_key_rings(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_mac_sign(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_mac_sign(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_mac_verify(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_mac_verify(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_raw_decrypt(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_raw_decrypt(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_raw_encrypt(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_raw_encrypt(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_restore_crypto_key_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_restore_crypto_key_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_crypto_key(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_crypto_key(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_crypto_key_primary_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_crypto_key_primary_version(self, response): - logging.log(f"Received response: {response}") - return response - - def pre_update_crypto_key_version(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_update_crypto_key_version(self, response): - logging.log(f"Received response: {response}") - return response - - transport = KeyManagementServiceRestTransport(interceptor=MyCustomKeyManagementServiceInterceptor()) - client = KeyManagementServiceClient(transport=transport) - - - """ - def pre_asymmetric_decrypt(self, request: service.AsymmetricDecryptRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.AsymmetricDecryptRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for asymmetric_decrypt - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_asymmetric_decrypt(self, response: service.AsymmetricDecryptResponse) -> service.AsymmetricDecryptResponse: - """Post-rpc interceptor for asymmetric_decrypt - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_asymmetric_sign(self, request: service.AsymmetricSignRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.AsymmetricSignRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for asymmetric_sign - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_asymmetric_sign(self, response: service.AsymmetricSignResponse) -> service.AsymmetricSignResponse: - """Post-rpc interceptor for asymmetric_sign - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_create_crypto_key(self, request: service.CreateCryptoKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateCryptoKeyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_crypto_key - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_create_crypto_key(self, response: resources.CryptoKey) -> resources.CryptoKey: - """Post-rpc interceptor for create_crypto_key - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_create_crypto_key_version(self, request: service.CreateCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_crypto_key_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_create_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: - """Post-rpc interceptor for create_crypto_key_version - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_create_import_job(self, request: service.CreateImportJobRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateImportJobRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_import_job - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_create_import_job(self, response: resources.ImportJob) -> resources.ImportJob: - """Post-rpc interceptor for create_import_job - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_create_key_ring(self, request: service.CreateKeyRingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.CreateKeyRingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for create_key_ring - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_create_key_ring(self, response: resources.KeyRing) -> resources.KeyRing: - """Post-rpc interceptor for create_key_ring - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_decrypt(self, request: service.DecryptRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DecryptRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for decrypt - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_decrypt(self, response: service.DecryptResponse) -> service.DecryptResponse: - """Post-rpc interceptor for decrypt - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_destroy_crypto_key_version(self, request: service.DestroyCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.DestroyCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for destroy_crypto_key_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_destroy_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: - """Post-rpc interceptor for destroy_crypto_key_version - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_encrypt(self, request: service.EncryptRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.EncryptRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for encrypt - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_encrypt(self, response: service.EncryptResponse) -> service.EncryptResponse: - """Post-rpc interceptor for encrypt - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_generate_random_bytes(self, request: service.GenerateRandomBytesRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GenerateRandomBytesRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for generate_random_bytes - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_generate_random_bytes(self, response: service.GenerateRandomBytesResponse) -> service.GenerateRandomBytesResponse: - """Post-rpc interceptor for generate_random_bytes - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_get_crypto_key(self, request: service.GetCryptoKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetCryptoKeyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_crypto_key - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_get_crypto_key(self, response: resources.CryptoKey) -> resources.CryptoKey: - """Post-rpc interceptor for get_crypto_key - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_get_crypto_key_version(self, request: service.GetCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_crypto_key_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_get_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: - """Post-rpc interceptor for get_crypto_key_version - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_get_import_job(self, request: service.GetImportJobRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetImportJobRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_import_job - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_get_import_job(self, response: resources.ImportJob) -> resources.ImportJob: - """Post-rpc interceptor for get_import_job - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_get_key_ring(self, request: service.GetKeyRingRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetKeyRingRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_key_ring - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_get_key_ring(self, response: resources.KeyRing) -> resources.KeyRing: - """Post-rpc interceptor for get_key_ring - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_get_public_key(self, request: service.GetPublicKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.GetPublicKeyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_public_key - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_get_public_key(self, response: resources.PublicKey) -> resources.PublicKey: - """Post-rpc interceptor for get_public_key - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_import_crypto_key_version(self, request: service.ImportCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ImportCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for import_crypto_key_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_import_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: - """Post-rpc interceptor for import_crypto_key_version - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_list_crypto_keys(self, request: service.ListCryptoKeysRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListCryptoKeysRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_crypto_keys - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_list_crypto_keys(self, response: service.ListCryptoKeysResponse) -> service.ListCryptoKeysResponse: - """Post-rpc interceptor for list_crypto_keys - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_list_crypto_key_versions(self, request: service.ListCryptoKeyVersionsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListCryptoKeyVersionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_crypto_key_versions - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_list_crypto_key_versions(self, response: service.ListCryptoKeyVersionsResponse) -> service.ListCryptoKeyVersionsResponse: - """Post-rpc interceptor for list_crypto_key_versions - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_list_import_jobs(self, request: service.ListImportJobsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListImportJobsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_import_jobs - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_list_import_jobs(self, response: service.ListImportJobsResponse) -> service.ListImportJobsResponse: - """Post-rpc interceptor for list_import_jobs - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_list_key_rings(self, request: service.ListKeyRingsRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.ListKeyRingsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_key_rings - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_list_key_rings(self, response: service.ListKeyRingsResponse) -> service.ListKeyRingsResponse: - """Post-rpc interceptor for list_key_rings - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_mac_sign(self, request: service.MacSignRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.MacSignRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for mac_sign - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_mac_sign(self, response: service.MacSignResponse) -> service.MacSignResponse: - """Post-rpc interceptor for mac_sign - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_mac_verify(self, request: service.MacVerifyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.MacVerifyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for mac_verify - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_mac_verify(self, response: service.MacVerifyResponse) -> service.MacVerifyResponse: - """Post-rpc interceptor for mac_verify - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_raw_decrypt(self, request: service.RawDecryptRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RawDecryptRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for raw_decrypt - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_raw_decrypt(self, response: service.RawDecryptResponse) -> service.RawDecryptResponse: - """Post-rpc interceptor for raw_decrypt - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_raw_encrypt(self, request: service.RawEncryptRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RawEncryptRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for raw_encrypt - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_raw_encrypt(self, response: service.RawEncryptResponse) -> service.RawEncryptResponse: - """Post-rpc interceptor for raw_encrypt - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_restore_crypto_key_version(self, request: service.RestoreCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.RestoreCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for restore_crypto_key_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_restore_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: - """Post-rpc interceptor for restore_crypto_key_version - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_update_crypto_key(self, request: service.UpdateCryptoKeyRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateCryptoKeyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_crypto_key - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_update_crypto_key(self, response: resources.CryptoKey) -> resources.CryptoKey: - """Post-rpc interceptor for update_crypto_key - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_update_crypto_key_primary_version(self, request: service.UpdateCryptoKeyPrimaryVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateCryptoKeyPrimaryVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_crypto_key_primary_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_update_crypto_key_primary_version(self, response: resources.CryptoKey) -> resources.CryptoKey: - """Post-rpc interceptor for update_crypto_key_primary_version - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_update_crypto_key_version(self, request: service.UpdateCryptoKeyVersionRequest, metadata: Sequence[Tuple[str, str]]) -> Tuple[service.UpdateCryptoKeyVersionRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for update_crypto_key_version - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_update_crypto_key_version(self, response: resources.CryptoKeyVersion) -> resources.CryptoKeyVersion: - """Post-rpc interceptor for update_crypto_key_version - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_get_location( - self, request: locations_pb2.GetLocationRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.GetLocationRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_location - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_list_locations( - self, request: locations_pb2.ListLocationsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[locations_pb2.ListLocationsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for list_locations - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_get_iam_policy( - self, request: iam_policy_pb2.GetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_get_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_set_iam_policy( - self, request: iam_policy_pb2.SetIamPolicyRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_set_iam_policy( - self, response: policy_pb2.Policy - ) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService server but before - it is returned to user code. - """ - return response - - def pre_test_iam_permissions( - self, request: iam_policy_pb2.TestIamPermissionsRequest, metadata: Sequence[Tuple[str, str]] - ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the request or metadata - before they are sent to the KeyManagementService server. - """ - return request, metadata - - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions - - Override in a subclass to manipulate the response - after it is returned by the KeyManagementService 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 KeyManagementService 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 KeyManagementService server but before - it is returned to user code. - """ - return response - - -@dataclasses.dataclass -class KeyManagementServiceRestStub: - _session: AuthorizedSession - _host: str - _interceptor: KeyManagementServiceRestInterceptor - - -class KeyManagementServiceRestTransport(_BaseKeyManagementServiceRestTransport): - """REST backend synchronous transport for KeyManagementService. - - Google Cloud Key Management Service - - Manages cryptographic keys and operations using those keys. - Implements a REST model with the following objects: - - - [KeyRing][google.cloud.kms.v1.KeyRing] - - [CryptoKey][google.cloud.kms.v1.CryptoKey] - - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - - [ImportJob][google.cloud.kms.v1.ImportJob] - - If you are using manual gRPC libraries, see `Using gRPC with Cloud - KMS `__. - - 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 = 'cloudkms.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[KeyManagementServiceRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client - certificate to configure mutual TLS HTTP channel. It is ignored - if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. - # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the - # credentials object - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - url_scheme=url_scheme, - api_audience=api_audience - ) - self._session = AuthorizedSession( - self._credentials, default_host=self.DEFAULT_HOST) - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or KeyManagementServiceRestInterceptor() - self._prep_wrapped_messages(client_info) - - class _AsymmetricDecrypt(_BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.AsymmetricDecrypt") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.AsymmetricDecryptRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.AsymmetricDecryptResponse: - r"""Call the asymmetric decrypt method over HTTP. - - Args: - request (~.service.AsymmetricDecryptRequest): - The request object. Request message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.AsymmetricDecryptResponse: - Response message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt._get_http_options() - request, metadata = self._interceptor.pre_asymmetric_decrypt(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._AsymmetricDecrypt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.AsymmetricDecryptResponse() - pb_resp = service.AsymmetricDecryptResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_asymmetric_decrypt(resp) - return resp - - class _AsymmetricSign(_BaseKeyManagementServiceRestTransport._BaseAsymmetricSign, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.AsymmetricSign") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.AsymmetricSignRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.AsymmetricSignResponse: - r"""Call the asymmetric sign method over HTTP. - - Args: - request (~.service.AsymmetricSignRequest): - The request object. Request message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.AsymmetricSignResponse: - Response message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseAsymmetricSign._get_http_options() - request, metadata = self._interceptor.pre_asymmetric_sign(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseAsymmetricSign._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseAsymmetricSign._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseAsymmetricSign._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._AsymmetricSign._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.AsymmetricSignResponse() - pb_resp = service.AsymmetricSignResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_asymmetric_sign(resp) - return resp - - class _CreateCryptoKey(_BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.CreateCryptoKey") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.CreateCryptoKeyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.CryptoKey: - r"""Call the create crypto key method over HTTP. - - Args: - request (~.service.CreateCryptoKeyRequest): - The request object. Request message for - [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey._get_http_options() - request, metadata = self._interceptor.pre_create_crypto_key(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._CreateCryptoKey._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.CryptoKey() - pb_resp = resources.CryptoKey.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_crypto_key(resp) - return resp - - class _CreateCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.CreateCryptoKeyVersion") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.CreateCryptoKeyVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.CryptoKeyVersion: - r"""Call the create crypto key version method over HTTP. - - Args: - request (~.service.CreateCryptoKeyVersionRequest): - The request object. Request message for - [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion._get_http_options() - request, metadata = self._interceptor.pre_create_crypto_key_version(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._CreateCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.CryptoKeyVersion() - pb_resp = resources.CryptoKeyVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_crypto_key_version(resp) - return resp - - class _CreateImportJob(_BaseKeyManagementServiceRestTransport._BaseCreateImportJob, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.CreateImportJob") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.CreateImportJobRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.ImportJob: - r"""Call the create import job method over HTTP. - - Args: - request (~.service.CreateImportJobRequest): - The request object. Request message for - [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be - used to create - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - using pre-existing key material, generated outside of - Cloud KMS. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", which - is a public/private key pair. You use the wrapping key - to encrypt (also known as wrap) the pre-existing key - material to protect it during the import process. The - nature of the wrapping key depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be set - to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be used - to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 - days after it is created. Once expired, Cloud KMS will - no longer be able to import or unwrap any key material - that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. - - For more information, see `Importing a - key `__. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseCreateImportJob._get_http_options() - request, metadata = self._interceptor.pre_create_import_job(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseCreateImportJob._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseCreateImportJob._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseCreateImportJob._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._CreateImportJob._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.ImportJob() - pb_resp = resources.ImportJob.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_import_job(resp) - return resp - - class _CreateKeyRing(_BaseKeyManagementServiceRestTransport._BaseCreateKeyRing, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.CreateKeyRing") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.CreateKeyRingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.KeyRing: - r"""Call the create key ring method over HTTP. - - Args: - request (~.service.CreateKeyRingRequest): - The request object. Request message for - [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel - logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseCreateKeyRing._get_http_options() - request, metadata = self._interceptor.pre_create_key_ring(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseCreateKeyRing._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseCreateKeyRing._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseCreateKeyRing._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._CreateKeyRing._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.KeyRing() - pb_resp = resources.KeyRing.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_create_key_ring(resp) - return resp - - class _Decrypt(_BaseKeyManagementServiceRestTransport._BaseDecrypt, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.Decrypt") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.DecryptRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.DecryptResponse: - r"""Call the decrypt method over HTTP. - - Args: - request (~.service.DecryptRequest): - The request object. Request message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.DecryptResponse: - Response message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseDecrypt._get_http_options() - request, metadata = self._interceptor.pre_decrypt(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseDecrypt._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseDecrypt._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseDecrypt._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._Decrypt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.DecryptResponse() - pb_resp = service.DecryptResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_decrypt(resp) - return resp - - class _DestroyCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.DestroyCryptoKeyVersion") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.DestroyCryptoKeyVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.CryptoKeyVersion: - r"""Call the destroy crypto key - version method over HTTP. - - Args: - request (~.service.DestroyCryptoKeyVersionRequest): - The request object. Request message for - [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion._get_http_options() - request, metadata = self._interceptor.pre_destroy_crypto_key_version(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._DestroyCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.CryptoKeyVersion() - pb_resp = resources.CryptoKeyVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_destroy_crypto_key_version(resp) - return resp - - class _Encrypt(_BaseKeyManagementServiceRestTransport._BaseEncrypt, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.Encrypt") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.EncryptRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.EncryptResponse: - r"""Call the encrypt method over HTTP. - - Args: - request (~.service.EncryptRequest): - The request object. Request message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.EncryptResponse: - Response message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseEncrypt._get_http_options() - request, metadata = self._interceptor.pre_encrypt(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseEncrypt._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseEncrypt._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseEncrypt._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._Encrypt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.EncryptResponse() - pb_resp = service.EncryptResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_encrypt(resp) - return resp - - class _GenerateRandomBytes(_BaseKeyManagementServiceRestTransport._BaseGenerateRandomBytes, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.GenerateRandomBytes") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.GenerateRandomBytesRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.GenerateRandomBytesResponse: - r"""Call the generate random bytes method over HTTP. - - Args: - request (~.service.GenerateRandomBytesRequest): - The request object. Request message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.GenerateRandomBytesResponse: - Response message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseGenerateRandomBytes._get_http_options() - request, metadata = self._interceptor.pre_generate_random_bytes(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGenerateRandomBytes._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseGenerateRandomBytes._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseGenerateRandomBytes._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._GenerateRandomBytes._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.GenerateRandomBytesResponse() - pb_resp = service.GenerateRandomBytesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_generate_random_bytes(resp) - return resp - - class _GetCryptoKey(_BaseKeyManagementServiceRestTransport._BaseGetCryptoKey, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.GetCryptoKey") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GetCryptoKeyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.CryptoKey: - r"""Call the get crypto key method over HTTP. - - Args: - request (~.service.GetCryptoKeyRequest): - The request object. Request message for - [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKey._get_http_options() - request, metadata = self._interceptor.pre_get_crypto_key(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKey._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKey._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._GetCryptoKey._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.CryptoKey() - pb_resp = resources.CryptoKey.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_crypto_key(resp) - return resp - - class _GetCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseGetCryptoKeyVersion, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.GetCryptoKeyVersion") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GetCryptoKeyVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.CryptoKeyVersion: - r"""Call the get crypto key version method over HTTP. - - Args: - request (~.service.GetCryptoKeyVersionRequest): - The request object. Request message for - [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKeyVersion._get_http_options() - request, metadata = self._interceptor.pre_get_crypto_key_version(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKeyVersion._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseGetCryptoKeyVersion._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._GetCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.CryptoKeyVersion() - pb_resp = resources.CryptoKeyVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_crypto_key_version(resp) - return resp - - class _GetImportJob(_BaseKeyManagementServiceRestTransport._BaseGetImportJob, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.GetImportJob") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GetImportJobRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.ImportJob: - r"""Call the get import job method over HTTP. - - Args: - request (~.service.GetImportJobRequest): - The request object. Request message for - [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.ImportJob: - An [ImportJob][google.cloud.kms.v1.ImportJob] can be - used to create - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - using pre-existing key material, generated outside of - Cloud KMS. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is - created, Cloud KMS will generate a "wrapping key", which - is a public/private key pair. You use the wrapping key - to encrypt (also known as wrap) the pre-existing key - material to protect it during the import process. The - nature of the wrapping key depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. - When the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be set - to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - and the - [public_key][google.cloud.kms.v1.ImportJob.public_key] - can be fetched. The fetched public key can then be used - to wrap your pre-existing key material. - - Once the key material is wrapped, it can be imported - into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - in an existing - [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS - uses the private key portion of the wrapping key to - unwrap the key material. Only Cloud KMS has access to - the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 - days after it is created. Once expired, Cloud KMS will - no longer be able to import or unwrap any key material - that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. - - For more information, see `Importing a - key `__. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseGetImportJob._get_http_options() - request, metadata = self._interceptor.pre_get_import_job(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetImportJob._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseGetImportJob._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._GetImportJob._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.ImportJob() - pb_resp = resources.ImportJob.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_import_job(resp) - return resp - - class _GetKeyRing(_BaseKeyManagementServiceRestTransport._BaseGetKeyRing, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.GetKeyRing") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GetKeyRingRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.KeyRing: - r"""Call the get key ring method over HTTP. - - Args: - request (~.service.GetKeyRingRequest): - The request object. Request message for - [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.KeyRing: - A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel - logical grouping of - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseGetKeyRing._get_http_options() - request, metadata = self._interceptor.pre_get_key_ring(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetKeyRing._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseGetKeyRing._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._GetKeyRing._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.KeyRing() - pb_resp = resources.KeyRing.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_key_ring(resp) - return resp - - class _GetPublicKey(_BaseKeyManagementServiceRestTransport._BaseGetPublicKey, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.GetPublicKey") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.GetPublicKeyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.PublicKey: - r"""Call the get public key method over HTTP. - - Args: - request (~.service.GetPublicKeyRequest): - The request object. Request message for - [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.PublicKey: - The public keys for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - Obtained via - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseGetPublicKey._get_http_options() - request, metadata = self._interceptor.pre_get_public_key(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetPublicKey._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseGetPublicKey._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._GetPublicKey._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.PublicKey() - pb_resp = resources.PublicKey.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_public_key(resp) - return resp - - class _ImportCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.ImportCryptoKeyVersion") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.ImportCryptoKeyVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.CryptoKeyVersion: - r"""Call the import crypto key version method over HTTP. - - Args: - request (~.service.ImportCryptoKeyVersionRequest): - The request object. Request message for - [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion._get_http_options() - request, metadata = self._interceptor.pre_import_crypto_key_version(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._ImportCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.CryptoKeyVersion() - pb_resp = resources.CryptoKeyVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_import_crypto_key_version(resp) - return resp - - class _ListCryptoKeys(_BaseKeyManagementServiceRestTransport._BaseListCryptoKeys, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.ListCryptoKeys") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.ListCryptoKeysRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.ListCryptoKeysResponse: - r"""Call the list crypto keys method over HTTP. - - Args: - request (~.service.ListCryptoKeysRequest): - The request object. Request message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.ListCryptoKeysResponse: - Response message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeys._get_http_options() - request, metadata = self._interceptor.pre_list_crypto_keys(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeys._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeys._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._ListCryptoKeys._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.ListCryptoKeysResponse() - pb_resp = service.ListCryptoKeysResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_crypto_keys(resp) - return resp - - class _ListCryptoKeyVersions(_BaseKeyManagementServiceRestTransport._BaseListCryptoKeyVersions, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.ListCryptoKeyVersions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.ListCryptoKeyVersionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.ListCryptoKeyVersionsResponse: - r"""Call the list crypto key versions method over HTTP. - - Args: - request (~.service.ListCryptoKeyVersionsRequest): - The request object. Request message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.ListCryptoKeyVersionsResponse: - Response message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeyVersions._get_http_options() - request, metadata = self._interceptor.pre_list_crypto_key_versions(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeyVersions._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseListCryptoKeyVersions._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._ListCryptoKeyVersions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.ListCryptoKeyVersionsResponse() - pb_resp = service.ListCryptoKeyVersionsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_crypto_key_versions(resp) - return resp - - class _ListImportJobs(_BaseKeyManagementServiceRestTransport._BaseListImportJobs, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.ListImportJobs") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.ListImportJobsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.ListImportJobsResponse: - r"""Call the list import jobs method over HTTP. - - Args: - request (~.service.ListImportJobsRequest): - The request object. Request message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.ListImportJobsResponse: - Response message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseListImportJobs._get_http_options() - request, metadata = self._interceptor.pre_list_import_jobs(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseListImportJobs._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseListImportJobs._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._ListImportJobs._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.ListImportJobsResponse() - pb_resp = service.ListImportJobsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_import_jobs(resp) - return resp - - class _ListKeyRings(_BaseKeyManagementServiceRestTransport._BaseListKeyRings, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.ListKeyRings") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: service.ListKeyRingsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.ListKeyRingsResponse: - r"""Call the list key rings method over HTTP. - - Args: - request (~.service.ListKeyRingsRequest): - The request object. Request message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.ListKeyRingsResponse: - Response message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseListKeyRings._get_http_options() - request, metadata = self._interceptor.pre_list_key_rings(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseListKeyRings._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseListKeyRings._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._ListKeyRings._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.ListKeyRingsResponse() - pb_resp = service.ListKeyRingsResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_key_rings(resp) - return resp - - class _MacSign(_BaseKeyManagementServiceRestTransport._BaseMacSign, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.MacSign") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.MacSignRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.MacSignResponse: - r"""Call the mac sign method over HTTP. - - Args: - request (~.service.MacSignRequest): - The request object. Request message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.MacSignResponse: - Response message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseMacSign._get_http_options() - request, metadata = self._interceptor.pre_mac_sign(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseMacSign._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseMacSign._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseMacSign._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._MacSign._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.MacSignResponse() - pb_resp = service.MacSignResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_mac_sign(resp) - return resp - - class _MacVerify(_BaseKeyManagementServiceRestTransport._BaseMacVerify, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.MacVerify") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.MacVerifyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.MacVerifyResponse: - r"""Call the mac verify method over HTTP. - - Args: - request (~.service.MacVerifyRequest): - The request object. Request message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.MacVerifyResponse: - Response message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseMacVerify._get_http_options() - request, metadata = self._interceptor.pre_mac_verify(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseMacVerify._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseMacVerify._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseMacVerify._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._MacVerify._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.MacVerifyResponse() - pb_resp = service.MacVerifyResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_mac_verify(resp) - return resp - - class _RawDecrypt(_BaseKeyManagementServiceRestTransport._BaseRawDecrypt, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.RawDecrypt") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.RawDecryptRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.RawDecryptResponse: - r"""Call the raw decrypt method over HTTP. - - Args: - request (~.service.RawDecryptRequest): - The request object. Request message for - [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.RawDecryptResponse: - Response message for - [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseRawDecrypt._get_http_options() - request, metadata = self._interceptor.pre_raw_decrypt(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseRawDecrypt._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseRawDecrypt._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseRawDecrypt._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._RawDecrypt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.RawDecryptResponse() - pb_resp = service.RawDecryptResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_raw_decrypt(resp) - return resp - - class _RawEncrypt(_BaseKeyManagementServiceRestTransport._BaseRawEncrypt, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.RawEncrypt") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.RawEncryptRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> service.RawEncryptResponse: - r"""Call the raw encrypt method over HTTP. - - Args: - request (~.service.RawEncryptRequest): - The request object. Request message for - [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.service.RawEncryptResponse: - Response message for - [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseRawEncrypt._get_http_options() - request, metadata = self._interceptor.pre_raw_encrypt(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseRawEncrypt._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseRawEncrypt._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseRawEncrypt._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._RawEncrypt._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = service.RawEncryptResponse() - pb_resp = service.RawEncryptResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_raw_encrypt(resp) - return resp - - class _RestoreCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.RestoreCryptoKeyVersion") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.RestoreCryptoKeyVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.CryptoKeyVersion: - r"""Call the restore crypto key - version method over HTTP. - - Args: - request (~.service.RestoreCryptoKeyVersionRequest): - The request object. Request message for - [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion._get_http_options() - request, metadata = self._interceptor.pre_restore_crypto_key_version(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._RestoreCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.CryptoKeyVersion() - pb_resp = resources.CryptoKeyVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_restore_crypto_key_version(resp) - return resp - - class _UpdateCryptoKey(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.UpdateCryptoKey") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.UpdateCryptoKeyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.CryptoKey: - r"""Call the update crypto key method over HTTP. - - Args: - request (~.service.UpdateCryptoKeyRequest): - The request object. Request message for - [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey._get_http_options() - request, metadata = self._interceptor.pre_update_crypto_key(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._UpdateCryptoKey._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.CryptoKey() - pb_resp = resources.CryptoKey.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_crypto_key(resp) - return resp - - class _UpdateCryptoKeyPrimaryVersion(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.UpdateCryptoKeyPrimaryVersion") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.UpdateCryptoKeyPrimaryVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.CryptoKey: - r"""Call the update crypto key primary - version method over HTTP. - - Args: - request (~.service.UpdateCryptoKeyPrimaryVersionRequest): - The request object. Request message for - [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.CryptoKey: - A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents - a logical key that can be used for cryptographic - operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up - of zero or more - [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic - operations. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion._get_http_options() - request, metadata = self._interceptor.pre_update_crypto_key_primary_version(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._UpdateCryptoKeyPrimaryVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.CryptoKey() - pb_resp = resources.CryptoKey.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_crypto_key_primary_version(resp) - return resp - - class _UpdateCryptoKeyVersion(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.UpdateCryptoKeyVersion") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: service.UpdateCryptoKeyVersionRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> resources.CryptoKeyVersion: - r"""Call the update crypto key version method over HTTP. - - Args: - request (~.service.UpdateCryptoKeyVersionRequest): - The request object. Request message for - [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.resources.CryptoKeyVersion: - A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the - associated key material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key material - represented by a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - can never be viewed or exported. It can only be used to - encrypt, decrypt, or sign data when an authorized user - or application invokes Cloud KMS. - - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion._get_http_options() - request, metadata = self._interceptor.pre_update_crypto_key_version(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._UpdateCryptoKeyVersion._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - # Return the response - resp = resources.CryptoKeyVersion() - pb_resp = resources.CryptoKeyVersion.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_crypto_key_version(resp) - return resp - - @property - def asymmetric_decrypt(self) -> Callable[ - [service.AsymmetricDecryptRequest], - service.AsymmetricDecryptResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AsymmetricDecrypt(self._session, self._host, self._interceptor) # type: ignore - - @property - def asymmetric_sign(self) -> Callable[ - [service.AsymmetricSignRequest], - service.AsymmetricSignResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._AsymmetricSign(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_crypto_key(self) -> Callable[ - [service.CreateCryptoKeyRequest], - resources.CryptoKey]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateCryptoKey(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_crypto_key_version(self) -> Callable[ - [service.CreateCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_import_job(self) -> Callable[ - [service.CreateImportJobRequest], - resources.ImportJob]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateImportJob(self._session, self._host, self._interceptor) # type: ignore - - @property - def create_key_ring(self) -> Callable[ - [service.CreateKeyRingRequest], - resources.KeyRing]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._CreateKeyRing(self._session, self._host, self._interceptor) # type: ignore - - @property - def decrypt(self) -> Callable[ - [service.DecryptRequest], - service.DecryptResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Decrypt(self._session, self._host, self._interceptor) # type: ignore - - @property - def destroy_crypto_key_version(self) -> Callable[ - [service.DestroyCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._DestroyCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def encrypt(self) -> Callable[ - [service.EncryptRequest], - service.EncryptResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._Encrypt(self._session, self._host, self._interceptor) # type: ignore - - @property - def generate_random_bytes(self) -> Callable[ - [service.GenerateRandomBytesRequest], - service.GenerateRandomBytesResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GenerateRandomBytes(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_crypto_key(self) -> Callable[ - [service.GetCryptoKeyRequest], - resources.CryptoKey]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetCryptoKey(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_crypto_key_version(self) -> Callable[ - [service.GetCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_import_job(self) -> Callable[ - [service.GetImportJobRequest], - resources.ImportJob]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetImportJob(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_key_ring(self) -> Callable[ - [service.GetKeyRingRequest], - resources.KeyRing]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetKeyRing(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_public_key(self) -> Callable[ - [service.GetPublicKeyRequest], - resources.PublicKey]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._GetPublicKey(self._session, self._host, self._interceptor) # type: ignore - - @property - def import_crypto_key_version(self) -> Callable[ - [service.ImportCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ImportCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_crypto_keys(self) -> Callable[ - [service.ListCryptoKeysRequest], - service.ListCryptoKeysResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListCryptoKeys(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_crypto_key_versions(self) -> Callable[ - [service.ListCryptoKeyVersionsRequest], - service.ListCryptoKeyVersionsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListCryptoKeyVersions(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_import_jobs(self) -> Callable[ - [service.ListImportJobsRequest], - service.ListImportJobsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListImportJobs(self._session, self._host, self._interceptor) # type: ignore - - @property - def list_key_rings(self) -> Callable[ - [service.ListKeyRingsRequest], - service.ListKeyRingsResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._ListKeyRings(self._session, self._host, self._interceptor) # type: ignore - - @property - def mac_sign(self) -> Callable[ - [service.MacSignRequest], - service.MacSignResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._MacSign(self._session, self._host, self._interceptor) # type: ignore - - @property - def mac_verify(self) -> Callable[ - [service.MacVerifyRequest], - service.MacVerifyResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._MacVerify(self._session, self._host, self._interceptor) # type: ignore - - @property - def raw_decrypt(self) -> Callable[ - [service.RawDecryptRequest], - service.RawDecryptResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._RawDecrypt(self._session, self._host, self._interceptor) # type: ignore - - @property - def raw_encrypt(self) -> Callable[ - [service.RawEncryptRequest], - service.RawEncryptResponse]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._RawEncrypt(self._session, self._host, self._interceptor) # type: ignore - - @property - def restore_crypto_key_version(self) -> Callable[ - [service.RestoreCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._RestoreCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_crypto_key(self) -> Callable[ - [service.UpdateCryptoKeyRequest], - resources.CryptoKey]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateCryptoKey(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_crypto_key_primary_version(self) -> Callable[ - [service.UpdateCryptoKeyPrimaryVersionRequest], - resources.CryptoKey]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateCryptoKeyPrimaryVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def update_crypto_key_version(self) -> Callable[ - [service.UpdateCryptoKeyVersionRequest], - resources.CryptoKeyVersion]: - # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. - # In C++ this would require a dynamic_cast - return self._UpdateCryptoKeyVersion(self._session, self._host, self._interceptor) # type: ignore - - @property - def get_location(self): - return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore - - class _GetLocation(_BaseKeyManagementServiceRestTransport._BaseGetLocation, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.GetLocation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.GetLocationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.Location: - - r"""Call the get location method over HTTP. - - Args: - request (locations_pb2.GetLocationRequest): - The request object for GetLocation method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.Location: Response from GetLocation method. - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseGetLocation._get_http_options() - request, metadata = self._interceptor.pre_get_location(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetLocation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseGetLocation._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._GetLocation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.Location() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_location(resp) - return resp - - @property - def list_locations(self): - return self._ListLocations(self._session, self._host, self._interceptor) # type: ignore - - class _ListLocations(_BaseKeyManagementServiceRestTransport._BaseListLocations, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.ListLocations") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: locations_pb2.ListLocationsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> locations_pb2.ListLocationsResponse: - - r"""Call the list locations method over HTTP. - - Args: - request (locations_pb2.ListLocationsRequest): - The request object for ListLocations method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - locations_pb2.ListLocationsResponse: Response from ListLocations method. - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseListLocations._get_http_options() - request, metadata = self._interceptor.pre_list_locations(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseListLocations._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseListLocations._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._ListLocations._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = locations_pb2.ListLocationsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_list_locations(resp) - return resp - - @property - def get_iam_policy(self): - return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _GetIamPolicy(_BaseKeyManagementServiceRestTransport._BaseGetIamPolicy, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.GetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: iam_policy_pb2.GetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the get iam policy method over HTTP. - - Args: - request (iam_policy_pb2.GetIamPolicyRequest): - The request object for GetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from GetIamPolicy method. - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseGetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetIamPolicy._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseGetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._GetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_iam_policy(resp) - return resp - - @property - def set_iam_policy(self): - return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore - - class _SetIamPolicy(_BaseKeyManagementServiceRestTransport._BaseSetIamPolicy, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.SetIamPolicy") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.SetIamPolicyRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> policy_pb2.Policy: - - r"""Call the set iam policy method over HTTP. - - Args: - request (iam_policy_pb2.SetIamPolicyRequest): - The request object for SetIamPolicy method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - policy_pb2.Policy: Response from SetIamPolicy method. - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseSetIamPolicy._get_http_options() - request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseSetIamPolicy._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseSetIamPolicy._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseSetIamPolicy._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._SetIamPolicy._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = policy_pb2.Policy() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_set_iam_policy(resp) - return resp - - @property - def test_iam_permissions(self): - return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore - - class _TestIamPermissions(_BaseKeyManagementServiceRestTransport._BaseTestIamPermissions, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.TestIamPermissions") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, - ) - return response - - def __call__(self, - request: iam_policy_pb2.TestIamPermissionsRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, str]]=(), - ) -> iam_policy_pb2.TestIamPermissionsResponse: - - r"""Call the test iam permissions method over HTTP. - - Args: - request (iam_policy_pb2.TestIamPermissionsRequest): - The request object for TestIamPermissions method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - iam_policy_pb2.TestIamPermissionsResponse: Response from TestIamPermissions method. - """ - - http_options = _BaseKeyManagementServiceRestTransport._BaseTestIamPermissions._get_http_options() - request, metadata = self._interceptor.pre_test_iam_permissions(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseTestIamPermissions._get_transcoded_request(http_options, request) - - body = _BaseKeyManagementServiceRestTransport._BaseTestIamPermissions._get_request_body_json(transcoded_request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseTestIamPermissions._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._TestIamPermissions._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request, body) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = iam_policy_pb2.TestIamPermissionsResponse() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_test_iam_permissions(resp) - return resp - - @property - def get_operation(self): - return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore - - class _GetOperation(_BaseKeyManagementServiceRestTransport._BaseGetOperation, KeyManagementServiceRestStub): - def __hash__(self): - return hash("KeyManagementServiceRestTransport.GetOperation") - - @staticmethod - def _get_response( - host, - metadata, - query_params, - session, - timeout, - transcoded_request, - body=None): - - uri = transcoded_request['uri'] - method = transcoded_request['method'] - headers = dict(metadata) - headers['Content-Type'] = 'application/json' - response = getattr(session, method)( - "{host}{uri}".format(host=host, uri=uri), - timeout=timeout, - headers=headers, - params=rest_helpers.flatten_query_params(query_params, strict=True), - ) - return response - - def __call__(self, - request: operations_pb2.GetOperationRequest, *, - retry: OptionalRetry=gapic_v1.method.DEFAULT, - timeout: Optional[float]=None, - metadata: Sequence[Tuple[str, 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 = _BaseKeyManagementServiceRestTransport._BaseGetOperation._get_http_options() - request, metadata = self._interceptor.pre_get_operation(request, metadata) - transcoded_request = _BaseKeyManagementServiceRestTransport._BaseGetOperation._get_transcoded_request(http_options, request) - - # Jsonify the query params - query_params = _BaseKeyManagementServiceRestTransport._BaseGetOperation._get_query_params_json(transcoded_request) - - # Send the request - response = KeyManagementServiceRestTransport._GetOperation._get_response(self._host, metadata, query_params, self._session, timeout, transcoded_request) - - # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception - # subclass. - if response.status_code >= 400: - raise core_exceptions.from_http_response(response) - - content = response.content.decode("utf-8") - resp = operations_pb2.Operation() - resp = json_format.Parse(content, resp) - resp = self._interceptor.post_get_operation(resp) - return resp - - @property - def kind(self) -> str: - return "rest" - - def close(self): - self._session.close() - - -__all__=( - 'KeyManagementServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py deleted file mode 100644 index 895c4a385558..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py +++ /dev/null @@ -1,1532 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import json # type: ignore -from google.api_core import path_template -from google.api_core import gapic_v1 - -from google.protobuf import json_format -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.cloud.location import locations_pb2 # type: ignore -from .base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO - -import re -from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union - - -from google.cloud.kms_v1.types import resources -from google.cloud.kms_v1.types import service -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore - - -class _BaseKeyManagementServiceRestTransport(KeyManagementServiceTransport): - """Base REST backend transport for KeyManagementService. - - Note: This class is not meant to be used directly. Use its sync and - async sub-classes instead. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends JSON representations of protocol buffers over HTTP/1.1 - """ - - def __init__(self, *, - host: str = 'cloudkms.googleapis.com', - credentials: Optional[Any] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - always_use_jwt_access: Optional[bool] = False, - url_scheme: str = 'https', - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. - Args: - host (Optional[str]): - The hostname to connect to (default: 'cloudkms.googleapis.com'). - credentials (Optional[Any]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you are developing - your own client library. - always_use_jwt_access (Optional[bool]): Whether self signed JWT should - be used for service account credentials. - url_scheme: the protocol scheme for the API endpoint. Normally - "https", but for testing or local servers, - "http" can be specified. - """ - # Run the base constructor - maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) - if maybe_url_match is None: - raise ValueError(f"Unexpected hostname structure: {host}") # pragma: NO COVER - - url_match_items = maybe_url_match.groupdict() - - host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host - - super().__init__( - host=host, - credentials=credentials, - client_info=client_info, - always_use_jwt_access=always_use_jwt_access, - api_audience=api_audience - ) - - class _BaseAsymmetricDecrypt: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricDecrypt', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.AsymmetricDecryptRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseAsymmetricDecrypt._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseAsymmetricSign: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricSign', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.AsymmetricSignRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseAsymmetricSign._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateCryptoKey: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "cryptoKeyId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys', - 'body': 'crypto_key', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.CreateCryptoKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseCreateCryptoKey._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateCryptoKeyVersion: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions', - 'body': 'crypto_key_version', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.CreateCryptoKeyVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseCreateCryptoKeyVersion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateImportJob: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "importJobId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*}/importJobs', - 'body': 'import_job', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.CreateImportJobRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseCreateImportJob._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseCreateKeyRing: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "keyRingId" : "", } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*}/keyRings', - 'body': 'key_ring', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.CreateKeyRingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseCreateKeyRing._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDecrypt: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}:decrypt', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.DecryptRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseDecrypt._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseDestroyCryptoKeyVersion: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:destroy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.DestroyCryptoKeyVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseDestroyCryptoKeyVersion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseEncrypt: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/**}:encrypt', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.EncryptRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseEncrypt._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGenerateRandomBytes: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{location=projects/*/locations/*}:generateRandomBytes', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GenerateRandomBytesRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetCryptoKey: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GetCryptoKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseGetCryptoKey._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetCryptoKeyVersion: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GetCryptoKeyVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseGetCryptoKeyVersion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetImportJob: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/importJobs/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GetImportJobRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseGetImportJob._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetKeyRing: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GetKeyRingRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseGetKeyRing._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetPublicKey: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}/publicKey', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.GetPublicKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseGetPublicKey._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseImportCryptoKeyVersion: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions:import', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.ImportCryptoKeyVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseImportCryptoKeyVersion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListCryptoKeys: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.ListCryptoKeysRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseListCryptoKeys._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListCryptoKeyVersions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.ListCryptoKeyVersionsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseListCryptoKeyVersions._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListImportJobs: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*/keyRings/*}/importJobs', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.ListImportJobsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseListImportJobs._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseListKeyRings: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{parent=projects/*/locations/*}/keyRings', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.ListKeyRingsRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseListKeyRings._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseMacSign: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macSign', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.MacSignRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseMacSign._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseMacVerify: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macVerify', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.MacVerifyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseMacVerify._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseRawDecrypt: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:rawDecrypt', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.RawDecryptRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseRawDecrypt._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseRawEncrypt: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:rawEncrypt', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.RawEncryptRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseRawEncrypt._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseRestoreCryptoKeyVersion: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:restore', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.RestoreCryptoKeyVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseRestoreCryptoKeyVersion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateCryptoKey: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{crypto_key.name=projects/*/locations/*/keyRings/*/cryptoKeys/*}', - 'body': 'crypto_key', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.UpdateCryptoKeyRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKey._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateCryptoKeyPrimaryVersion: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}:updatePrimaryVersion', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.UpdateCryptoKeyPrimaryVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyPrimaryVersion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseUpdateCryptoKeyVersion: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask" : {}, } - - @classmethod - def _get_unset_required_fields(cls, message_dict): - return {k: v for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() if k not in message_dict} - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'patch', - 'uri': '/v1/{crypto_key_version.name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}', - 'body': 'crypto_key_version', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - pb_request = service.UpdateCryptoKeyVersionRequest.pb(request) - transcoded_request = path_template.transcode(http_options, pb_request) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - # Jsonify the request body - - body = json_format.MessageToJson( - transcoded_request['body'], - use_integers_for_enums=True - ) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json_format.MessageToJson( - transcoded_request['query_params'], - use_integers_for_enums=True, - )) - query_params.update(_BaseKeyManagementServiceRestTransport._BaseUpdateCryptoKeyVersion._get_unset_required_fields(query_params)) - - query_params["$alt"] = "json;enum-encoding=int" - return query_params - - class _BaseGetLocation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseListLocations: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*}/locations', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:getIamPolicy', - }, - { - 'method': 'get', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:getIamPolicy', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseSetIamPolicy: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:setIamPolicy', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:setIamPolicy', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseTestIamPermissions: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/cryptoKeys/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/keyRings/*/importJobs/*}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConfig}:testIamPermissions', - 'body': '*', - }, - { - 'method': 'post', - 'uri': '/v1/{resource=projects/*/locations/*/ekmConnections/*}:testIamPermissions', - 'body': '*', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_request_body_json(transcoded_request): - body = json.dumps(transcoded_request['body']) - return body - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - class _BaseGetOperation: - def __hash__(self): # pragma: NO COVER - return NotImplementedError("__hash__ must be implemented.") - - @staticmethod - def _get_http_options(): - http_options: List[Dict[str, str]] = [{ - 'method': 'get', - 'uri': '/v1/{name=projects/*/locations/*/operations/*}', - }, - ] - return http_options - - @staticmethod - def _get_transcoded_request(http_options, request): - request_kwargs = json_format.MessageToDict(request) - transcoded_request = path_template.transcode( - http_options, **request_kwargs) - return transcoded_request - - @staticmethod - def _get_query_params_json(transcoded_request): - query_params = json.loads(json.dumps(transcoded_request['query_params'])) - return query_params - - -__all__=( - '_BaseKeyManagementServiceRestTransport', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/__init__.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/__init__.py deleted file mode 100644 index c5fb762a3035..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/__init__.py +++ /dev/null @@ -1,182 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from .autokey import ( - CreateKeyHandleMetadata, - CreateKeyHandleRequest, - GetKeyHandleRequest, - KeyHandle, - ListKeyHandlesRequest, - ListKeyHandlesResponse, -) -from .autokey_admin import ( - AutokeyConfig, - GetAutokeyConfigRequest, - ShowEffectiveAutokeyConfigRequest, - ShowEffectiveAutokeyConfigResponse, - UpdateAutokeyConfigRequest, -) -from .ekm_service import ( - Certificate, - CreateEkmConnectionRequest, - EkmConfig, - EkmConnection, - GetEkmConfigRequest, - GetEkmConnectionRequest, - ListEkmConnectionsRequest, - ListEkmConnectionsResponse, - UpdateEkmConfigRequest, - UpdateEkmConnectionRequest, - VerifyConnectivityRequest, - VerifyConnectivityResponse, -) -from .resources import ( - CryptoKey, - CryptoKeyVersion, - CryptoKeyVersionTemplate, - ExternalProtectionLevelOptions, - ImportJob, - KeyAccessJustificationsPolicy, - KeyOperationAttestation, - KeyRing, - PublicKey, - AccessReason, - ProtectionLevel, -) -from .service import ( - AsymmetricDecryptRequest, - AsymmetricDecryptResponse, - AsymmetricSignRequest, - AsymmetricSignResponse, - CreateCryptoKeyRequest, - CreateCryptoKeyVersionRequest, - CreateImportJobRequest, - CreateKeyRingRequest, - DecryptRequest, - DecryptResponse, - DestroyCryptoKeyVersionRequest, - Digest, - EncryptRequest, - EncryptResponse, - GenerateRandomBytesRequest, - GenerateRandomBytesResponse, - GetCryptoKeyRequest, - GetCryptoKeyVersionRequest, - GetImportJobRequest, - GetKeyRingRequest, - GetPublicKeyRequest, - ImportCryptoKeyVersionRequest, - ListCryptoKeysRequest, - ListCryptoKeysResponse, - ListCryptoKeyVersionsRequest, - ListCryptoKeyVersionsResponse, - ListImportJobsRequest, - ListImportJobsResponse, - ListKeyRingsRequest, - ListKeyRingsResponse, - LocationMetadata, - MacSignRequest, - MacSignResponse, - MacVerifyRequest, - MacVerifyResponse, - RawDecryptRequest, - RawDecryptResponse, - RawEncryptRequest, - RawEncryptResponse, - RestoreCryptoKeyVersionRequest, - UpdateCryptoKeyPrimaryVersionRequest, - UpdateCryptoKeyRequest, - UpdateCryptoKeyVersionRequest, -) - -__all__ = ( - 'CreateKeyHandleMetadata', - 'CreateKeyHandleRequest', - 'GetKeyHandleRequest', - 'KeyHandle', - 'ListKeyHandlesRequest', - 'ListKeyHandlesResponse', - 'AutokeyConfig', - 'GetAutokeyConfigRequest', - 'ShowEffectiveAutokeyConfigRequest', - 'ShowEffectiveAutokeyConfigResponse', - 'UpdateAutokeyConfigRequest', - 'Certificate', - 'CreateEkmConnectionRequest', - 'EkmConfig', - 'EkmConnection', - 'GetEkmConfigRequest', - 'GetEkmConnectionRequest', - 'ListEkmConnectionsRequest', - 'ListEkmConnectionsResponse', - 'UpdateEkmConfigRequest', - 'UpdateEkmConnectionRequest', - 'VerifyConnectivityRequest', - 'VerifyConnectivityResponse', - 'CryptoKey', - 'CryptoKeyVersion', - 'CryptoKeyVersionTemplate', - 'ExternalProtectionLevelOptions', - 'ImportJob', - 'KeyAccessJustificationsPolicy', - 'KeyOperationAttestation', - 'KeyRing', - 'PublicKey', - 'AccessReason', - 'ProtectionLevel', - 'AsymmetricDecryptRequest', - 'AsymmetricDecryptResponse', - 'AsymmetricSignRequest', - 'AsymmetricSignResponse', - 'CreateCryptoKeyRequest', - 'CreateCryptoKeyVersionRequest', - 'CreateImportJobRequest', - 'CreateKeyRingRequest', - 'DecryptRequest', - 'DecryptResponse', - 'DestroyCryptoKeyVersionRequest', - 'Digest', - 'EncryptRequest', - 'EncryptResponse', - 'GenerateRandomBytesRequest', - 'GenerateRandomBytesResponse', - 'GetCryptoKeyRequest', - 'GetCryptoKeyVersionRequest', - 'GetImportJobRequest', - 'GetKeyRingRequest', - 'GetPublicKeyRequest', - 'ImportCryptoKeyVersionRequest', - 'ListCryptoKeysRequest', - 'ListCryptoKeysResponse', - 'ListCryptoKeyVersionsRequest', - 'ListCryptoKeyVersionsResponse', - 'ListImportJobsRequest', - 'ListImportJobsResponse', - 'ListKeyRingsRequest', - 'ListKeyRingsResponse', - 'LocationMetadata', - 'MacSignRequest', - 'MacSignResponse', - 'MacVerifyRequest', - 'MacVerifyResponse', - 'RawDecryptRequest', - 'RawDecryptResponse', - 'RawEncryptRequest', - 'RawEncryptResponse', - 'RestoreCryptoKeyVersionRequest', - 'UpdateCryptoKeyPrimaryVersionRequest', - 'UpdateCryptoKeyRequest', - 'UpdateCryptoKeyVersionRequest', -) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey.py deleted file mode 100644 index 42fcb9aaec75..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey.py +++ /dev/null @@ -1,214 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.kms.v1', - manifest={ - 'CreateKeyHandleRequest', - 'GetKeyHandleRequest', - 'KeyHandle', - 'CreateKeyHandleMetadata', - 'ListKeyHandlesRequest', - 'ListKeyHandlesResponse', - }, -) - - -class CreateKeyHandleRequest(proto.Message): - r"""Request message for - [Autokey.CreateKeyHandle][google.cloud.kms.v1.Autokey.CreateKeyHandle]. - - Attributes: - parent (str): - Required. Name of the resource project and location to - create the [KeyHandle][google.cloud.kms.v1.KeyHandle] in, - e.g. ``projects/{PROJECT_ID}/locations/{LOCATION}``. - key_handle_id (str): - Optional. Id of the - [KeyHandle][google.cloud.kms.v1.KeyHandle]. Must be unique - to the resource project and location. If not provided by the - caller, a new UUID is used. - key_handle (google.cloud.kms_v1.types.KeyHandle): - Required. [KeyHandle][google.cloud.kms.v1.KeyHandle] to - create. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - key_handle_id: str = proto.Field( - proto.STRING, - number=2, - ) - key_handle: 'KeyHandle' = proto.Field( - proto.MESSAGE, - number=3, - message='KeyHandle', - ) - - -class GetKeyHandleRequest(proto.Message): - r"""Request message for - [GetKeyHandle][google.cloud.kms.v1.Autokey.GetKeyHandle]. - - Attributes: - name (str): - Required. Name of the - [KeyHandle][google.cloud.kms.v1.KeyHandle] resource, e.g. - ``projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class KeyHandle(proto.Message): - r"""Resource-oriented representation of a request to Cloud KMS Autokey - and the resulting provisioning of a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Attributes: - name (str): - Identifier. Name of the - [KeyHandle][google.cloud.kms.v1.KeyHandle] resource, e.g. - ``projects/{PROJECT_ID}/locations/{LOCATION}/keyHandles/{KEY_HANDLE_ID}``. - kms_key (str): - Output only. Name of a - [CryptoKey][google.cloud.kms.v1.CryptoKey] that has been - provisioned for Customer Managed Encryption Key (CMEK) use - in the [KeyHandle][google.cloud.kms.v1.KeyHandle] project - and location for the requested resource type. The - [CryptoKey][google.cloud.kms.v1.CryptoKey] project will - reflect the value configured in the - [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] on the - resource project's ancestor folder at the time of the - [KeyHandle][google.cloud.kms.v1.KeyHandle] creation. If more - than one ancestor folder has a configured - [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig], the - nearest of these configurations is used. - resource_type_selector (str): - Required. Indicates the resource type that the resulting - [CryptoKey][google.cloud.kms.v1.CryptoKey] is meant to - protect, e.g. ``{SERVICE}.googleapis.com/{TYPE}``. See - documentation for supported resource types. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - kms_key: str = proto.Field( - proto.STRING, - number=3, - ) - resource_type_selector: str = proto.Field( - proto.STRING, - number=4, - ) - - -class CreateKeyHandleMetadata(proto.Message): - r"""Metadata message for - [CreateKeyHandle][google.cloud.kms.v1.Autokey.CreateKeyHandle] - long-running operation response. - - """ - - -class ListKeyHandlesRequest(proto.Message): - r"""Request message for - [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. - - Attributes: - parent (str): - Required. Name of the resource project and location from - which to list [KeyHandles][google.cloud.kms.v1.KeyHandle], - e.g. ``projects/{PROJECT_ID}/locations/{LOCATION}``. - page_size (int): - Optional. Optional limit on the number of - [KeyHandles][google.cloud.kms.v1.KeyHandle] to include in - the response. The service may return fewer than this value. - Further [KeyHandles][google.cloud.kms.v1.KeyHandle] can - subsequently be obtained by including the - [ListKeyHandlesResponse.next_page_token][google.cloud.kms.v1.ListKeyHandlesResponse.next_page_token] - in a subsequent request. If unspecified, at most 100 - [KeyHandles][google.cloud.kms.v1.KeyHandle] will be - returned. - page_token (str): - Optional. Optional pagination token, returned earlier via - [ListKeyHandlesResponse.next_page_token][google.cloud.kms.v1.ListKeyHandlesResponse.next_page_token]. - filter (str): - Optional. Filter to apply when listing - [KeyHandles][google.cloud.kms.v1.KeyHandle], e.g. - ``resource_type_selector="{SERVICE}.googleapis.com/{TYPE}"``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - - -class ListKeyHandlesResponse(proto.Message): - r"""Response message for - [Autokey.ListKeyHandles][google.cloud.kms.v1.Autokey.ListKeyHandles]. - - Attributes: - key_handles (MutableSequence[google.cloud.kms_v1.types.KeyHandle]): - Resulting [KeyHandles][google.cloud.kms.v1.KeyHandle]. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - [ListKeyHandlesRequest.page_token][google.cloud.kms.v1.ListKeyHandlesRequest.page_token] - to retrieve the next page of results. - """ - - @property - def raw_page(self): - return self - - key_handles: MutableSequence['KeyHandle'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='KeyHandle', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey_admin.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey_admin.py deleted file mode 100644 index 1c7ec9aaa444..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/autokey_admin.py +++ /dev/null @@ -1,178 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 - - -__protobuf__ = proto.module( - package='google.cloud.kms.v1', - manifest={ - 'UpdateAutokeyConfigRequest', - 'GetAutokeyConfigRequest', - 'AutokeyConfig', - 'ShowEffectiveAutokeyConfigRequest', - 'ShowEffectiveAutokeyConfigResponse', - }, -) - - -class UpdateAutokeyConfigRequest(proto.Message): - r"""Request message for - [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig]. - - Attributes: - autokey_config (google.cloud.kms_v1.types.AutokeyConfig): - Required. [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] - with values to update. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Masks which fields of the - [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] to - update, e.g. ``keyProject``. - """ - - autokey_config: 'AutokeyConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='AutokeyConfig', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetAutokeyConfigRequest(proto.Message): - r"""Request message for - [GetAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig]. - - Attributes: - name (str): - Required. Name of the - [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] resource, - e.g. ``folders/{FOLDER_NUMBER}/autokeyConfig``. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class AutokeyConfig(proto.Message): - r"""Cloud KMS Autokey configuration for a folder. - - Attributes: - name (str): - Identifier. Name of the - [AutokeyConfig][google.cloud.kms.v1.AutokeyConfig] resource, - e.g. ``folders/{FOLDER_NUMBER}/autokeyConfig``. - key_project (str): - Optional. Name of the key project, e.g. - ``projects/{PROJECT_ID}`` or ``projects/{PROJECT_NUMBER}``, - where Cloud KMS Autokey will provision a new - [CryptoKey][google.cloud.kms.v1.CryptoKey] when a - [KeyHandle][google.cloud.kms.v1.KeyHandle] is created. On - [UpdateAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig], - the caller will require ``cloudkms.cryptoKeys.setIamPolicy`` - permission on this key project. Once configured, for Cloud - KMS Autokey to function properly, this key project must have - the Cloud KMS API activated and the Cloud KMS Service Agent - for this key project must be granted the ``cloudkms.admin`` - role (or pertinent permissions). A request with an empty key - project field will clear the configuration. - state (google.cloud.kms_v1.types.AutokeyConfig.State): - Output only. The state for the AutokeyConfig. - """ - class State(proto.Enum): - r"""The states AutokeyConfig can be in. - - Values: - STATE_UNSPECIFIED (0): - The state of the AutokeyConfig is - unspecified. - ACTIVE (1): - The AutokeyConfig is currently active. - KEY_PROJECT_DELETED (2): - A previously configured key project has been - deleted and the current AutokeyConfig is - unusable. - UNINITIALIZED (3): - The AutokeyConfig is not yet initialized or - has been reset to its default uninitialized - state. - """ - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - KEY_PROJECT_DELETED = 2 - UNINITIALIZED = 3 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - key_project: str = proto.Field( - proto.STRING, - number=2, - ) - state: State = proto.Field( - proto.ENUM, - number=4, - enum=State, - ) - - -class ShowEffectiveAutokeyConfigRequest(proto.Message): - r"""Request message for - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - - Attributes: - parent (str): - Required. Name of the resource project to the - show effective Cloud KMS Autokey configuration - for. This may be helpful for interrogating the - effect of nested folder configurations on a - given resource project. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - - -class ShowEffectiveAutokeyConfigResponse(proto.Message): - r"""Response message for - [ShowEffectiveAutokeyConfig][google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig]. - - Attributes: - key_project (str): - Name of the key project configured in the - resource project's folder ancestry. - """ - - key_project: str = proto.Field( - proto.STRING, - number=1, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/ekm_service.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/ekm_service.py deleted file mode 100644 index 3db4aba34db2..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/ekm_service.py +++ /dev/null @@ -1,554 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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.kms.v1', - manifest={ - 'ListEkmConnectionsRequest', - 'ListEkmConnectionsResponse', - 'GetEkmConnectionRequest', - 'CreateEkmConnectionRequest', - 'UpdateEkmConnectionRequest', - 'GetEkmConfigRequest', - 'UpdateEkmConfigRequest', - 'Certificate', - 'EkmConnection', - 'EkmConfig', - 'VerifyConnectivityRequest', - 'VerifyConnectivityResponse', - }, -) - - -class ListEkmConnectionsRequest(proto.Message): - r"""Request message for - [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. - - Attributes: - parent (str): - Required. The resource name of the location associated with - the [EkmConnections][google.cloud.kms.v1.EkmConnection] to - list, in the format ``projects/*/locations/*``. - page_size (int): - Optional. Optional limit on the number of - [EkmConnections][google.cloud.kms.v1.EkmConnection] to - include in the response. Further - [EkmConnections][google.cloud.kms.v1.EkmConnection] can - subsequently be obtained by including the - [ListEkmConnectionsResponse.next_page_token][google.cloud.kms.v1.ListEkmConnectionsResponse.next_page_token] - in a subsequent request. If unspecified, the server will - pick an appropriate default. - page_token (str): - Optional. Optional pagination token, returned earlier via - [ListEkmConnectionsResponse.next_page_token][google.cloud.kms.v1.ListEkmConnectionsResponse.next_page_token]. - filter (str): - Optional. Only include resources that match the filter in - the response. For more information, see `Sorting and - filtering list - results `__. - order_by (str): - Optional. Specify how the results should be sorted. If not - specified, the results will be sorted in the default order. - For more information, see `Sorting and filtering list - results `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListEkmConnectionsResponse(proto.Message): - r"""Response message for - [EkmService.ListEkmConnections][google.cloud.kms.v1.EkmService.ListEkmConnections]. - - Attributes: - ekm_connections (MutableSequence[google.cloud.kms_v1.types.EkmConnection]): - The list of - [EkmConnections][google.cloud.kms.v1.EkmConnection]. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - [ListEkmConnectionsRequest.page_token][google.cloud.kms.v1.ListEkmConnectionsRequest.page_token] - to retrieve the next page of results. - total_size (int): - The total number of - [EkmConnections][google.cloud.kms.v1.EkmConnection] that - matched the query. - """ - - @property - def raw_page(self): - return self - - ekm_connections: MutableSequence['EkmConnection'] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message='EkmConnection', - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class GetEkmConnectionRequest(proto.Message): - r"""Request message for - [EkmService.GetEkmConnection][google.cloud.kms.v1.EkmService.GetEkmConnection]. - - Attributes: - name (str): - Required. The [name][google.cloud.kms.v1.EkmConnection.name] - of the [EkmConnection][google.cloud.kms.v1.EkmConnection] to - get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateEkmConnectionRequest(proto.Message): - r"""Request message for - [EkmService.CreateEkmConnection][google.cloud.kms.v1.EkmService.CreateEkmConnection]. - - Attributes: - parent (str): - Required. The resource name of the location associated with - the [EkmConnection][google.cloud.kms.v1.EkmConnection], in - the format ``projects/*/locations/*``. - ekm_connection_id (str): - Required. It must be unique within a location and match the - regular expression ``[a-zA-Z0-9_-]{1,63}``. - ekm_connection (google.cloud.kms_v1.types.EkmConnection): - Required. An - [EkmConnection][google.cloud.kms.v1.EkmConnection] with - initial field values. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - ekm_connection_id: str = proto.Field( - proto.STRING, - number=2, - ) - ekm_connection: 'EkmConnection' = proto.Field( - proto.MESSAGE, - number=3, - message='EkmConnection', - ) - - -class UpdateEkmConnectionRequest(proto.Message): - r"""Request message for - [EkmService.UpdateEkmConnection][google.cloud.kms.v1.EkmService.UpdateEkmConnection]. - - Attributes: - ekm_connection (google.cloud.kms_v1.types.EkmConnection): - Required. [EkmConnection][google.cloud.kms.v1.EkmConnection] - with updated values. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - ekm_connection: 'EkmConnection' = proto.Field( - proto.MESSAGE, - number=1, - message='EkmConnection', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class GetEkmConfigRequest(proto.Message): - r"""Request message for - [EkmService.GetEkmConfig][google.cloud.kms.v1.EkmService.GetEkmConfig]. - - Attributes: - name (str): - Required. The [name][google.cloud.kms.v1.EkmConfig.name] of - the [EkmConfig][google.cloud.kms.v1.EkmConfig] to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class UpdateEkmConfigRequest(proto.Message): - r"""Request message for - [EkmService.UpdateEkmConfig][google.cloud.kms.v1.EkmService.UpdateEkmConfig]. - - Attributes: - ekm_config (google.cloud.kms_v1.types.EkmConfig): - Required. [EkmConfig][google.cloud.kms.v1.EkmConfig] with - updated values. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - ekm_config: 'EkmConfig' = proto.Field( - proto.MESSAGE, - number=1, - message='EkmConfig', - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class Certificate(proto.Message): - r"""A [Certificate][google.cloud.kms.v1.Certificate] represents an X.509 - certificate used to authenticate HTTPS connections to EKM replicas. - - Attributes: - raw_der (bytes): - Required. The raw certificate bytes in DER - format. - parsed (bool): - Output only. True if the certificate was - parsed successfully. - issuer (str): - Output only. The issuer distinguished name in RFC 2253 - format. Only present if - [parsed][google.cloud.kms.v1.Certificate.parsed] is true. - subject (str): - Output only. The subject distinguished name in RFC 2253 - format. Only present if - [parsed][google.cloud.kms.v1.Certificate.parsed] is true. - subject_alternative_dns_names (MutableSequence[str]): - Output only. The subject Alternative DNS names. Only present - if [parsed][google.cloud.kms.v1.Certificate.parsed] is true. - not_before_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The certificate is not valid before this time. - Only present if - [parsed][google.cloud.kms.v1.Certificate.parsed] is true. - not_after_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The certificate is not valid after this time. - Only present if - [parsed][google.cloud.kms.v1.Certificate.parsed] is true. - serial_number (str): - Output only. The certificate serial number as a hex string. - Only present if - [parsed][google.cloud.kms.v1.Certificate.parsed] is true. - sha256_fingerprint (str): - Output only. The SHA-256 certificate fingerprint as a hex - string. Only present if - [parsed][google.cloud.kms.v1.Certificate.parsed] is true. - """ - - raw_der: bytes = proto.Field( - proto.BYTES, - number=1, - ) - parsed: bool = proto.Field( - proto.BOOL, - number=2, - ) - issuer: str = proto.Field( - proto.STRING, - number=3, - ) - subject: str = proto.Field( - proto.STRING, - number=4, - ) - subject_alternative_dns_names: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=5, - ) - not_before_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - not_after_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - serial_number: str = proto.Field( - proto.STRING, - number=8, - ) - sha256_fingerprint: str = proto.Field( - proto.STRING, - number=9, - ) - - -class EkmConnection(proto.Message): - r"""An [EkmConnection][google.cloud.kms.v1.EkmConnection] represents an - individual EKM connection. It can be used for creating - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], as - well as performing cryptographic operations using keys created - within the [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - Attributes: - name (str): - Output only. The resource name for the - [EkmConnection][google.cloud.kms.v1.EkmConnection] in the - format ``projects/*/locations/*/ekmConnections/*``. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which the - [EkmConnection][google.cloud.kms.v1.EkmConnection] was - created. - service_resolvers (MutableSequence[google.cloud.kms_v1.types.EkmConnection.ServiceResolver]): - Optional. A list of - [ServiceResolvers][google.cloud.kms.v1.EkmConnection.ServiceResolver] - where the EKM can be reached. There should be one - ServiceResolver per EKM replica. Currently, only a single - [ServiceResolver][google.cloud.kms.v1.EkmConnection.ServiceResolver] - is supported. - etag (str): - Optional. Etag of the currently stored - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - key_management_mode (google.cloud.kms_v1.types.EkmConnection.KeyManagementMode): - Optional. Describes who can perform control plane operations - on the EKM. If unset, this defaults to - [MANUAL][google.cloud.kms.v1.EkmConnection.KeyManagementMode.MANUAL]. - crypto_space_path (str): - Optional. Identifies the EKM Crypto Space that this - [EkmConnection][google.cloud.kms.v1.EkmConnection] maps to. - Note: This field is required if - [KeyManagementMode][google.cloud.kms.v1.EkmConnection.KeyManagementMode] - is - [CLOUD_KMS][google.cloud.kms.v1.EkmConnection.KeyManagementMode.CLOUD_KMS]. - """ - class KeyManagementMode(proto.Enum): - r"""[KeyManagementMode][google.cloud.kms.v1.EkmConnection.KeyManagementMode] - describes who can perform control plane cryptographic operations - using this [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - Values: - KEY_MANAGEMENT_MODE_UNSPECIFIED (0): - Not specified. - MANUAL (1): - EKM-side key management operations on - [CryptoKeys][google.cloud.kms.v1.CryptoKey] created with - this [EkmConnection][google.cloud.kms.v1.EkmConnection] must - be initiated from the EKM directly and cannot be performed - from Cloud KMS. This means that: - - - When creating a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - associated with this - [EkmConnection][google.cloud.kms.v1.EkmConnection], the - caller must supply the key path of pre-existing external - key material that will be linked to the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - - Destruction of external key material cannot be requested - via the Cloud KMS API and must be performed directly in - the EKM. - - Automatic rotation of key material is not supported. - CLOUD_KMS (2): - All [CryptoKeys][google.cloud.kms.v1.CryptoKey] created with - this [EkmConnection][google.cloud.kms.v1.EkmConnection] use - EKM-side key management operations initiated from Cloud KMS. - This means that: - - - When a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - associated with this - [EkmConnection][google.cloud.kms.v1.EkmConnection] is - created, the EKM automatically generates new key material - and a new key path. The caller cannot supply the key path - of pre-existing external key material. - - Destruction of external key material associated with this - [EkmConnection][google.cloud.kms.v1.EkmConnection] can be - requested by calling - [DestroyCryptoKeyVersion][EkmService.DestroyCryptoKeyVersion]. - - Automatic rotation of key material is supported. - """ - KEY_MANAGEMENT_MODE_UNSPECIFIED = 0 - MANUAL = 1 - CLOUD_KMS = 2 - - class ServiceResolver(proto.Message): - r"""A - [ServiceResolver][google.cloud.kms.v1.EkmConnection.ServiceResolver] - represents an EKM replica that can be reached within an - [EkmConnection][google.cloud.kms.v1.EkmConnection]. - - Attributes: - service_directory_service (str): - Required. The resource name of the Service Directory service - pointing to an EKM replica, in the format - ``projects/*/locations/*/namespaces/*/services/*``. - endpoint_filter (str): - Optional. The filter applied to the endpoints - of the resolved service. If no filter is - specified, all endpoints will be considered. An - endpoint will be chosen arbitrarily from the - filtered list for each request. - - For endpoint filter syntax and examples, see - https://cloud.google.com/service-directory/docs/reference/rpc/google.cloud.servicedirectory.v1#resolveservicerequest. - hostname (str): - Required. The hostname of the EKM replica - used at TLS and HTTP layers. - server_certificates (MutableSequence[google.cloud.kms_v1.types.Certificate]): - Required. A list of leaf server certificates used to - authenticate HTTPS connections to the EKM replica. - Currently, a maximum of 10 - [Certificate][google.cloud.kms.v1.Certificate] is supported. - """ - - service_directory_service: str = proto.Field( - proto.STRING, - number=1, - ) - endpoint_filter: str = proto.Field( - proto.STRING, - number=2, - ) - hostname: str = proto.Field( - proto.STRING, - number=3, - ) - server_certificates: MutableSequence['Certificate'] = proto.RepeatedField( - proto.MESSAGE, - number=4, - message='Certificate', - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - service_resolvers: MutableSequence[ServiceResolver] = proto.RepeatedField( - proto.MESSAGE, - number=3, - message=ServiceResolver, - ) - etag: str = proto.Field( - proto.STRING, - number=5, - ) - key_management_mode: KeyManagementMode = proto.Field( - proto.ENUM, - number=6, - enum=KeyManagementMode, - ) - crypto_space_path: str = proto.Field( - proto.STRING, - number=7, - ) - - -class EkmConfig(proto.Message): - r"""An [EkmConfig][google.cloud.kms.v1.EkmConfig] is a singleton - resource that represents configuration parameters that apply to all - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] with a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC] in a - given project and location. - - Attributes: - name (str): - Output only. The resource name for the - [EkmConfig][google.cloud.kms.v1.EkmConfig] in the format - ``projects/*/locations/*/ekmConfig``. - default_ekm_connection (str): - Optional. Resource name of the default - [EkmConnection][google.cloud.kms.v1.EkmConnection]. Setting - this field to the empty string removes the default. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - default_ekm_connection: str = proto.Field( - proto.STRING, - number=2, - ) - - -class VerifyConnectivityRequest(proto.Message): - r"""Request message for - [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. - - Attributes: - name (str): - Required. The [name][google.cloud.kms.v1.EkmConnection.name] - of the [EkmConnection][google.cloud.kms.v1.EkmConnection] to - verify. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class VerifyConnectivityResponse(proto.Message): - r"""Response message for - [EkmService.VerifyConnectivity][google.cloud.kms.v1.EkmService.VerifyConnectivity]. - - """ - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/resources.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/resources.py deleted file mode 100644 index 090a67f7938c..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/resources.py +++ /dev/null @@ -1,1383 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES 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 duration_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.kms.v1', - manifest={ - 'ProtectionLevel', - 'AccessReason', - 'KeyRing', - 'CryptoKey', - 'CryptoKeyVersionTemplate', - 'KeyOperationAttestation', - 'CryptoKeyVersion', - 'PublicKey', - 'ImportJob', - 'ExternalProtectionLevelOptions', - 'KeyAccessJustificationsPolicy', - }, -) - - -class ProtectionLevel(proto.Enum): - r"""[ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] specifies how - cryptographic operations are performed. For more information, see - [Protection levels] - (https://cloud.google.com/kms/docs/algorithms#protection_levels). - - Values: - PROTECTION_LEVEL_UNSPECIFIED (0): - Not specified. - SOFTWARE (1): - Crypto operations are performed in software. - HSM (2): - Crypto operations are performed in a Hardware - Security Module. - EXTERNAL (3): - Crypto operations are performed by an - external key manager. - EXTERNAL_VPC (4): - Crypto operations are performed in an - EKM-over-VPC backend. - """ - PROTECTION_LEVEL_UNSPECIFIED = 0 - SOFTWARE = 1 - HSM = 2 - EXTERNAL = 3 - EXTERNAL_VPC = 4 - - -class AccessReason(proto.Enum): - r"""Describes the reason for a data access. Please refer to - https://cloud.google.com/assured-workloads/key-access-justifications/docs/justification-codes - for the detailed semantic meaning of justification reason codes. - - Values: - REASON_UNSPECIFIED (0): - Unspecified access reason. - CUSTOMER_INITIATED_SUPPORT (1): - Customer-initiated support. - GOOGLE_INITIATED_SERVICE (2): - Google-initiated access for system management - and troubleshooting. - THIRD_PARTY_DATA_REQUEST (3): - Google-initiated access in response to a - legal request or legal process. - GOOGLE_INITIATED_REVIEW (4): - Google-initiated access for security, fraud, - abuse, or compliance purposes. - CUSTOMER_INITIATED_ACCESS (5): - Customer uses their account to perform any - access to their own data which their IAM policy - authorizes. - GOOGLE_INITIATED_SYSTEM_OPERATION (6): - Google systems access customer data to help - optimize the structure of the data or quality - for future uses by the customer. - REASON_NOT_EXPECTED (7): - No reason is expected for this key request. - MODIFIED_CUSTOMER_INITIATED_ACCESS (8): - Customer uses their account to perform any access to their - own data which their IAM policy authorizes, and one of the - following is true: - - - A Google administrator has reset the root-access account - associated with the user's organization within the past 7 - days. - - A Google-initiated emergency access operation has - interacted with a resource in the same project or folder - as the currently accessed resource within the past 7 - days. - MODIFIED_GOOGLE_INITIATED_SYSTEM_OPERATION (9): - Google systems access customer data to help optimize the - structure of the data or quality for future uses by the - customer, and one of the following is true: - - - A Google administrator has reset the root-access account - associated with the user's organization within the past 7 - days. - - A Google-initiated emergency access operation has - interacted with a resource in the same project or folder - as the currently accessed resource within the past 7 - days. - GOOGLE_RESPONSE_TO_PRODUCTION_ALERT (10): - Google-initiated access to maintain system - reliability. - CUSTOMER_AUTHORIZED_WORKFLOW_SERVICING (11): - One of the following operations is being executed while - simultaneously encountering an internal technical issue - which prevented a more precise justification code from being - generated: - - - Your account has been used to perform any access to your - own data which your IAM policy authorizes. - - An automated Google system operates on encrypted customer - data which your IAM policy authorizes. - - Customer-initiated Google support access. - - Google-initiated support access to protect system - reliability. - """ - REASON_UNSPECIFIED = 0 - CUSTOMER_INITIATED_SUPPORT = 1 - GOOGLE_INITIATED_SERVICE = 2 - THIRD_PARTY_DATA_REQUEST = 3 - GOOGLE_INITIATED_REVIEW = 4 - CUSTOMER_INITIATED_ACCESS = 5 - GOOGLE_INITIATED_SYSTEM_OPERATION = 6 - REASON_NOT_EXPECTED = 7 - MODIFIED_CUSTOMER_INITIATED_ACCESS = 8 - MODIFIED_GOOGLE_INITIATED_SYSTEM_OPERATION = 9 - GOOGLE_RESPONSE_TO_PRODUCTION_ALERT = 10 - CUSTOMER_AUTHORIZED_WORKFLOW_SERVICING = 11 - - -class KeyRing(proto.Message): - r"""A [KeyRing][google.cloud.kms.v1.KeyRing] is a toplevel logical - grouping of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - - Attributes: - name (str): - Output only. The resource name for the - [KeyRing][google.cloud.kms.v1.KeyRing] in the format - ``projects/*/locations/*/keyRings/*``. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [KeyRing][google.cloud.kms.v1.KeyRing] was created. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=2, - message=timestamp_pb2.Timestamp, - ) - - -class CryptoKey(proto.Message): - r"""A [CryptoKey][google.cloud.kms.v1.CryptoKey] represents a logical - key that can be used for cryptographic operations. - - A [CryptoKey][google.cloud.kms.v1.CryptoKey] is made up of zero or - more [versions][google.cloud.kms.v1.CryptoKeyVersion], which - represent the actual key material used in cryptographic operations. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - name (str): - Output only. The resource name for this - [CryptoKey][google.cloud.kms.v1.CryptoKey] in the format - ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - primary (google.cloud.kms_v1.types.CryptoKeyVersion): - Output only. A copy of the "primary" - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - that will be used by - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] - when this [CryptoKey][google.cloud.kms.v1.CryptoKey] is - given in - [EncryptRequest.name][google.cloud.kms.v1.EncryptRequest.name]. - - The [CryptoKey][google.cloud.kms.v1.CryptoKey]'s primary - version can be updated via - [UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. - - Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] - may have a primary. For other keys, this field will be - omitted. - purpose (google.cloud.kms_v1.types.CryptoKey.CryptoKeyPurpose): - Immutable. The immutable purpose of this - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [CryptoKey][google.cloud.kms.v1.CryptoKey] was created. - next_rotation_time (google.protobuf.timestamp_pb2.Timestamp): - At - [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time], - the Key Management Service will automatically: - - 1. Create a new version of this - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - 2. Mark the new version as primary. - - Key rotations performed manually via - [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] - and - [UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion] - do not affect - [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time]. - - Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] - support automatic rotation. For other keys, this field must - be omitted. - rotation_period (google.protobuf.duration_pb2.Duration): - [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time] - will be advanced by this period when the service - automatically rotates a key. Must be at least 24 hours and - at most 876,000 hours. - - If - [rotation_period][google.cloud.kms.v1.CryptoKey.rotation_period] - is set, - [next_rotation_time][google.cloud.kms.v1.CryptoKey.next_rotation_time] - must also be set. - - Keys with [purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT] - support automatic rotation. For other keys, this field must - be omitted. - - This field is a member of `oneof`_ ``rotation_schedule``. - version_template (google.cloud.kms_v1.types.CryptoKeyVersionTemplate): - A template describing settings for new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - instances. The properties of new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - instances created by either - [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] - or auto-rotation are controlled by this template. - labels (MutableMapping[str, str]): - Labels with user-defined metadata. For more information, see - `Labeling - Keys `__. - import_only (bool): - Immutable. Whether this key may contain - imported versions only. - destroy_scheduled_duration (google.protobuf.duration_pb2.Duration): - Immutable. The period of time that versions of this key - spend in the - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED] - state before transitioning to - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED]. - If not specified at creation time, the default duration is - 30 days. - crypto_key_backend (str): - Immutable. The resource name of the backend environment - where the key material for all - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - associated with this - [CryptoKey][google.cloud.kms.v1.CryptoKey] reside and where - all related cryptographic operations are performed. Only - applicable if - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - have a - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] of - [EXTERNAL_VPC][CryptoKeyVersion.ProtectionLevel.EXTERNAL_VPC], - with the resource name in the format - ``projects/*/locations/*/ekmConnections/*``. Note, this list - is non-exhaustive and may apply to additional - [ProtectionLevels][google.cloud.kms.v1.ProtectionLevel] in - the future. - key_access_justifications_policy (google.cloud.kms_v1.types.KeyAccessJustificationsPolicy): - Optional. The policy used for Key Access - Justifications Policy Enforcement. If this field - is present and this key is enrolled in Key - Access Justifications Policy Enforcement, the - policy will be evaluated in encrypt, decrypt, - and sign operations, and the operation will fail - if rejected by the policy. The policy is defined - by specifying zero or more allowed justification - codes. - https://cloud.google.com/assured-workloads/key-access-justifications/docs/justification-codes - By default, this field is absent, and all - justification codes are allowed. - """ - class CryptoKeyPurpose(proto.Enum): - r"""[CryptoKeyPurpose][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose] - describes the cryptographic capabilities of a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. A given key can only be - used for the operations allowed by its purpose. For more - information, see `Key - purposes `__. - - Values: - CRYPTO_KEY_PURPOSE_UNSPECIFIED (0): - Not specified. - ENCRYPT_DECRYPT (1): - [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this - purpose may be used with - [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] - and - [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - ASYMMETRIC_SIGN (5): - [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this - purpose may be used with - [AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign] - and - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - ASYMMETRIC_DECRYPT (6): - [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this - purpose may be used with - [AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt] - and - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - RAW_ENCRYPT_DECRYPT (7): - [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this - purpose may be used with - [RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt] - and - [RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. - This purpose is meant to be used for interoperable symmetric - encryption and does not support automatic CryptoKey - rotation. - MAC (9): - [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this - purpose may be used with - [MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - """ - CRYPTO_KEY_PURPOSE_UNSPECIFIED = 0 - ENCRYPT_DECRYPT = 1 - ASYMMETRIC_SIGN = 5 - ASYMMETRIC_DECRYPT = 6 - RAW_ENCRYPT_DECRYPT = 7 - MAC = 9 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - primary: 'CryptoKeyVersion' = proto.Field( - proto.MESSAGE, - number=2, - message='CryptoKeyVersion', - ) - purpose: CryptoKeyPurpose = proto.Field( - proto.ENUM, - number=3, - enum=CryptoKeyPurpose, - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - next_rotation_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=7, - message=timestamp_pb2.Timestamp, - ) - rotation_period: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=8, - oneof='rotation_schedule', - message=duration_pb2.Duration, - ) - version_template: 'CryptoKeyVersionTemplate' = proto.Field( - proto.MESSAGE, - number=11, - message='CryptoKeyVersionTemplate', - ) - labels: MutableMapping[str, str] = proto.MapField( - proto.STRING, - proto.STRING, - number=10, - ) - import_only: bool = proto.Field( - proto.BOOL, - number=13, - ) - destroy_scheduled_duration: duration_pb2.Duration = proto.Field( - proto.MESSAGE, - number=14, - message=duration_pb2.Duration, - ) - crypto_key_backend: str = proto.Field( - proto.STRING, - number=15, - ) - key_access_justifications_policy: 'KeyAccessJustificationsPolicy' = proto.Field( - proto.MESSAGE, - number=17, - message='KeyAccessJustificationsPolicy', - ) - - -class CryptoKeyVersionTemplate(proto.Message): - r"""A - [CryptoKeyVersionTemplate][google.cloud.kms.v1.CryptoKeyVersionTemplate] - specifies the properties to use when creating a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], either - manually with - [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] - or automatically as a result of auto-rotation. - - Attributes: - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] to - use when creating a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - based on this template. Immutable. Defaults to - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE]. - algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): - Required. - [Algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] - to use when creating a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - based on this template. - - For backwards compatibility, GOOGLE_SYMMETRIC_ENCRYPTION is - implied if both this field is omitted and - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - is - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - """ - - protection_level: 'ProtectionLevel' = proto.Field( - proto.ENUM, - number=1, - enum='ProtectionLevel', - ) - algorithm: 'CryptoKeyVersion.CryptoKeyVersionAlgorithm' = proto.Field( - proto.ENUM, - number=3, - enum='CryptoKeyVersion.CryptoKeyVersionAlgorithm', - ) - - -class KeyOperationAttestation(proto.Message): - r"""Contains an HSM-generated attestation about a key operation. For - more information, see [Verifying attestations] - (https://cloud.google.com/kms/docs/attest-key). - - Attributes: - format_ (google.cloud.kms_v1.types.KeyOperationAttestation.AttestationFormat): - Output only. The format of the attestation - data. - content (bytes): - Output only. The attestation data provided by - the HSM when the key operation was performed. - cert_chains (google.cloud.kms_v1.types.KeyOperationAttestation.CertificateChains): - Output only. The certificate chains needed to - validate the attestation - """ - class AttestationFormat(proto.Enum): - r"""Attestation formats provided by the HSM. - - Values: - ATTESTATION_FORMAT_UNSPECIFIED (0): - Not specified. - CAVIUM_V1_COMPRESSED (3): - Cavium HSM attestation compressed with gzip. - Note that this format is defined by Cavium and - subject to change at any time. - - See - https://www.marvell.com/products/security-solutions/nitrox-hs-adapters/software-key-attestation.html. - CAVIUM_V2_COMPRESSED (4): - Cavium HSM attestation V2 compressed with - gzip. This is a new format introduced in - Cavium's version 3.2-08. - """ - ATTESTATION_FORMAT_UNSPECIFIED = 0 - CAVIUM_V1_COMPRESSED = 3 - CAVIUM_V2_COMPRESSED = 4 - - class CertificateChains(proto.Message): - r"""Certificate chains needed to verify the attestation. - Certificates in chains are PEM-encoded and are ordered based on - https://tools.ietf.org/html/rfc5246#section-7.4.2. - - Attributes: - cavium_certs (MutableSequence[str]): - Cavium certificate chain corresponding to the - attestation. - google_card_certs (MutableSequence[str]): - Google card certificate chain corresponding - to the attestation. - google_partition_certs (MutableSequence[str]): - Google partition certificate chain - corresponding to the attestation. - """ - - cavium_certs: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=1, - ) - google_card_certs: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=2, - ) - google_partition_certs: MutableSequence[str] = proto.RepeatedField( - proto.STRING, - number=3, - ) - - format_: AttestationFormat = proto.Field( - proto.ENUM, - number=4, - enum=AttestationFormat, - ) - content: bytes = proto.Field( - proto.BYTES, - number=5, - ) - cert_chains: CertificateChains = proto.Field( - proto.MESSAGE, - number=6, - message=CertificateChains, - ) - - -class CryptoKeyVersion(proto.Message): - r"""A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents an individual cryptographic key, and the associated key - material. - - An - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - version can be used for cryptographic operations. - - For security reasons, the raw cryptographic key material represented - by a [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] can - never be viewed or exported. It can only be used to encrypt, - decrypt, or sign data when an authorized user or application invokes - Cloud KMS. - - Attributes: - name (str): - Output only. The resource name for this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in - the format - ``projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*``. - state (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionState): - The current state of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - Output only. The - [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - describing how crypto operations are performed with this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): - Output only. The - [CryptoKeyVersionAlgorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] - that this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - supports. - attestation (google.cloud.kms_v1.types.KeyOperationAttestation): - Output only. Statement that was generated and signed by the - HSM at key creation time. Use this statement to verify - attributes of the key as stored on the HSM, independently of - Google. Only provided for key versions with - [protection_level][google.cloud.kms.v1.CryptoKeyVersion.protection_level] - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM]. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] was - created. - generate_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - key material was generated. - destroy_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - key material is scheduled for destruction. Only present if - [state][google.cloud.kms.v1.CryptoKeyVersion.state] is - [DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED]. - destroy_event_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this CryptoKeyVersion's key material - was destroyed. Only present if - [state][google.cloud.kms.v1.CryptoKeyVersion.state] is - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED]. - import_job (str): - Output only. The name of the - [ImportJob][google.cloud.kms.v1.ImportJob] used in the most - recent import of this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - Only present if the underlying key material was imported. - import_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - key material was most recently imported. - import_failure_reason (str): - Output only. The root cause of the most recent import - failure. Only present if - [state][google.cloud.kms.v1.CryptoKeyVersion.state] is - [IMPORT_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.IMPORT_FAILED]. - generation_failure_reason (str): - Output only. The root cause of the most recent generation - failure. Only present if - [state][google.cloud.kms.v1.CryptoKeyVersion.state] is - [GENERATION_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.GENERATION_FAILED]. - external_destruction_failure_reason (str): - Output only. The root cause of the most recent external - destruction failure. Only present if - [state][google.cloud.kms.v1.CryptoKeyVersion.state] is - [EXTERNAL_DESTRUCTION_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.EXTERNAL_DESTRUCTION_FAILED]. - external_protection_level_options (google.cloud.kms_v1.types.ExternalProtectionLevelOptions): - ExternalProtectionLevelOptions stores a group of additional - fields for configuring a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - that are specific to the - [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] - protection level and - [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] - protection levels. - reimport_eligible (bool): - Output only. Whether or not this key version is eligible for - reimport, by being specified as a target in - [ImportCryptoKeyVersionRequest.crypto_key_version][google.cloud.kms.v1.ImportCryptoKeyVersionRequest.crypto_key_version]. - """ - class CryptoKeyVersionAlgorithm(proto.Enum): - r"""The algorithm of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], indicating - what parameters must be used for each cryptographic operation. - - The - [GOOGLE_SYMMETRIC_ENCRYPTION][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION] - algorithm is usable with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. - - Algorithms beginning with ``RSA_SIGN_`` are usable with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN]. - - The fields in the name after ``RSA_SIGN_`` correspond to the - following parameters: padding algorithm, modulus bit length, and - digest algorithm. - - For PSS, the salt length used is equal to the length of digest - algorithm. For example, - [RSA_SIGN_PSS_2048_SHA256][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_SIGN_PSS_2048_SHA256] - will use PSS with a salt length of 256 bits or 32 bytes. - - Algorithms beginning with ``RSA_DECRYPT_`` are usable with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT]. - - The fields in the name after ``RSA_DECRYPT_`` correspond to the - following parameters: padding algorithm, modulus bit length, and - digest algorithm. - - Algorithms beginning with ``EC_SIGN_`` are usable with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - [ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN]. - - The fields in the name after ``EC_SIGN_`` correspond to the - following parameters: elliptic curve, digest algorithm. - - Algorithms beginning with ``HMAC_`` are usable with - [CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] - [MAC][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.MAC]. - - The suffix following ``HMAC_`` corresponds to the hash algorithm - being used (eg. SHA256). - - Algorithms beginning with ``PQ_`` are post-quantum. - - For more information, see [Key purposes and algorithms] - (https://cloud.google.com/kms/docs/algorithms). - - Values: - CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED (0): - Not specified. - GOOGLE_SYMMETRIC_ENCRYPTION (1): - Creates symmetric encryption keys. - AES_128_GCM (41): - AES-GCM (Galois Counter Mode) using 128-bit - keys. - AES_256_GCM (19): - AES-GCM (Galois Counter Mode) using 256-bit - keys. - AES_128_CBC (42): - AES-CBC (Cipher Block Chaining Mode) using - 128-bit keys. - AES_256_CBC (43): - AES-CBC (Cipher Block Chaining Mode) using - 256-bit keys. - AES_128_CTR (44): - AES-CTR (Counter Mode) using 128-bit keys. - AES_256_CTR (45): - AES-CTR (Counter Mode) using 256-bit keys. - RSA_SIGN_PSS_2048_SHA256 (2): - RSASSA-PSS 2048 bit key with a SHA256 digest. - RSA_SIGN_PSS_3072_SHA256 (3): - RSASSA-PSS 3072 bit key with a SHA256 digest. - RSA_SIGN_PSS_4096_SHA256 (4): - RSASSA-PSS 4096 bit key with a SHA256 digest. - RSA_SIGN_PSS_4096_SHA512 (15): - RSASSA-PSS 4096 bit key with a SHA512 digest. - RSA_SIGN_PKCS1_2048_SHA256 (5): - RSASSA-PKCS1-v1_5 with a 2048 bit key and a SHA256 digest. - RSA_SIGN_PKCS1_3072_SHA256 (6): - RSASSA-PKCS1-v1_5 with a 3072 bit key and a SHA256 digest. - RSA_SIGN_PKCS1_4096_SHA256 (7): - RSASSA-PKCS1-v1_5 with a 4096 bit key and a SHA256 digest. - RSA_SIGN_PKCS1_4096_SHA512 (16): - RSASSA-PKCS1-v1_5 with a 4096 bit key and a SHA512 digest. - RSA_SIGN_RAW_PKCS1_2048 (28): - RSASSA-PKCS1-v1_5 signing without encoding, with a 2048 bit - key. - RSA_SIGN_RAW_PKCS1_3072 (29): - RSASSA-PKCS1-v1_5 signing without encoding, with a 3072 bit - key. - RSA_SIGN_RAW_PKCS1_4096 (30): - RSASSA-PKCS1-v1_5 signing without encoding, with a 4096 bit - key. - RSA_DECRYPT_OAEP_2048_SHA256 (8): - RSAES-OAEP 2048 bit key with a SHA256 digest. - RSA_DECRYPT_OAEP_3072_SHA256 (9): - RSAES-OAEP 3072 bit key with a SHA256 digest. - RSA_DECRYPT_OAEP_4096_SHA256 (10): - RSAES-OAEP 4096 bit key with a SHA256 digest. - RSA_DECRYPT_OAEP_4096_SHA512 (17): - RSAES-OAEP 4096 bit key with a SHA512 digest. - RSA_DECRYPT_OAEP_2048_SHA1 (37): - RSAES-OAEP 2048 bit key with a SHA1 digest. - RSA_DECRYPT_OAEP_3072_SHA1 (38): - RSAES-OAEP 3072 bit key with a SHA1 digest. - RSA_DECRYPT_OAEP_4096_SHA1 (39): - RSAES-OAEP 4096 bit key with a SHA1 digest. - EC_SIGN_P256_SHA256 (12): - ECDSA on the NIST P-256 curve with a SHA256 digest. Other - hash functions can also be used: - https://cloud.google.com/kms/docs/create-validate-signatures#ecdsa_support_for_other_hash_algorithms - EC_SIGN_P384_SHA384 (13): - ECDSA on the NIST P-384 curve with a SHA384 digest. Other - hash functions can also be used: - https://cloud.google.com/kms/docs/create-validate-signatures#ecdsa_support_for_other_hash_algorithms - EC_SIGN_SECP256K1_SHA256 (31): - ECDSA on the non-NIST secp256k1 curve. This curve is only - supported for HSM protection level. Other hash functions can - also be used: - https://cloud.google.com/kms/docs/create-validate-signatures#ecdsa_support_for_other_hash_algorithms - EC_SIGN_ED25519 (40): - EdDSA on the Curve25519 in pure mode (taking - data as input). - HMAC_SHA256 (32): - HMAC-SHA256 signing with a 256 bit key. - HMAC_SHA1 (33): - HMAC-SHA1 signing with a 160 bit key. - HMAC_SHA384 (34): - HMAC-SHA384 signing with a 384 bit key. - HMAC_SHA512 (35): - HMAC-SHA512 signing with a 512 bit key. - HMAC_SHA224 (36): - HMAC-SHA224 signing with a 224 bit key. - EXTERNAL_SYMMETRIC_ENCRYPTION (18): - Algorithm representing symmetric encryption - by an external key manager. - """ - CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED = 0 - GOOGLE_SYMMETRIC_ENCRYPTION = 1 - AES_128_GCM = 41 - AES_256_GCM = 19 - AES_128_CBC = 42 - AES_256_CBC = 43 - AES_128_CTR = 44 - AES_256_CTR = 45 - RSA_SIGN_PSS_2048_SHA256 = 2 - RSA_SIGN_PSS_3072_SHA256 = 3 - RSA_SIGN_PSS_4096_SHA256 = 4 - RSA_SIGN_PSS_4096_SHA512 = 15 - RSA_SIGN_PKCS1_2048_SHA256 = 5 - RSA_SIGN_PKCS1_3072_SHA256 = 6 - RSA_SIGN_PKCS1_4096_SHA256 = 7 - RSA_SIGN_PKCS1_4096_SHA512 = 16 - RSA_SIGN_RAW_PKCS1_2048 = 28 - RSA_SIGN_RAW_PKCS1_3072 = 29 - RSA_SIGN_RAW_PKCS1_4096 = 30 - RSA_DECRYPT_OAEP_2048_SHA256 = 8 - RSA_DECRYPT_OAEP_3072_SHA256 = 9 - RSA_DECRYPT_OAEP_4096_SHA256 = 10 - RSA_DECRYPT_OAEP_4096_SHA512 = 17 - RSA_DECRYPT_OAEP_2048_SHA1 = 37 - RSA_DECRYPT_OAEP_3072_SHA1 = 38 - RSA_DECRYPT_OAEP_4096_SHA1 = 39 - EC_SIGN_P256_SHA256 = 12 - EC_SIGN_P384_SHA384 = 13 - EC_SIGN_SECP256K1_SHA256 = 31 - EC_SIGN_ED25519 = 40 - HMAC_SHA256 = 32 - HMAC_SHA1 = 33 - HMAC_SHA384 = 34 - HMAC_SHA512 = 35 - HMAC_SHA224 = 36 - EXTERNAL_SYMMETRIC_ENCRYPTION = 18 - - class CryptoKeyVersionState(proto.Enum): - r"""The state of a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], indicating - if it can be used. - - Values: - CRYPTO_KEY_VERSION_STATE_UNSPECIFIED (0): - Not specified. - PENDING_GENERATION (5): - This version is still being generated. It may not be used, - enabled, disabled, or destroyed yet. Cloud KMS will - automatically mark this version - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - as soon as the version is ready. - ENABLED (1): - This version may be used for cryptographic - operations. - DISABLED (2): - This version may not be used, but the key material is still - available, and the version can be placed back into the - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - state. - DESTROYED (3): - This version is destroyed, and the key material is no longer - stored. This version may only become - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - again if this version is - [reimport_eligible][google.cloud.kms.v1.CryptoKeyVersion.reimport_eligible] - and the original key material is reimported with a call to - [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - DESTROY_SCHEDULED (4): - This version is scheduled for destruction, and will be - destroyed soon. Call - [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] - to put it back into the - [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] - state. - PENDING_IMPORT (6): - This version is still being imported. It may not be used, - enabled, disabled, or destroyed yet. Cloud KMS will - automatically mark this version - [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] - as soon as the version is ready. - IMPORT_FAILED (7): - This version was not imported successfully. It may not be - used, enabled, disabled, or destroyed. The submitted key - material has been discarded. Additional details can be found - in - [CryptoKeyVersion.import_failure_reason][google.cloud.kms.v1.CryptoKeyVersion.import_failure_reason]. - GENERATION_FAILED (8): - This version was not generated successfully. It may not be - used, enabled, disabled, or destroyed. Additional details - can be found in - [CryptoKeyVersion.generation_failure_reason][google.cloud.kms.v1.CryptoKeyVersion.generation_failure_reason]. - PENDING_EXTERNAL_DESTRUCTION (9): - This version was destroyed, and it may not be - used or enabled again. Cloud KMS is waiting for - the corresponding key material residing in an - external key manager to be destroyed. - EXTERNAL_DESTRUCTION_FAILED (10): - This version was destroyed, and it may not be used or - enabled again. However, Cloud KMS could not confirm that the - corresponding key material residing in an external key - manager was destroyed. Additional details can be found in - [CryptoKeyVersion.external_destruction_failure_reason][google.cloud.kms.v1.CryptoKeyVersion.external_destruction_failure_reason]. - """ - CRYPTO_KEY_VERSION_STATE_UNSPECIFIED = 0 - PENDING_GENERATION = 5 - ENABLED = 1 - DISABLED = 2 - DESTROYED = 3 - DESTROY_SCHEDULED = 4 - PENDING_IMPORT = 6 - IMPORT_FAILED = 7 - GENERATION_FAILED = 8 - PENDING_EXTERNAL_DESTRUCTION = 9 - EXTERNAL_DESTRUCTION_FAILED = 10 - - class CryptoKeyVersionView(proto.Enum): - r"""A view for - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]s. Controls - the level of detail returned for - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] in - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions] - and - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - - Values: - CRYPTO_KEY_VERSION_VIEW_UNSPECIFIED (0): - Default view for each - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - Does not include the - [attestation][google.cloud.kms.v1.CryptoKeyVersion.attestation] - field. - FULL (1): - Provides all fields in each - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], - including the - [attestation][google.cloud.kms.v1.CryptoKeyVersion.attestation]. - """ - CRYPTO_KEY_VERSION_VIEW_UNSPECIFIED = 0 - FULL = 1 - - name: str = proto.Field( - proto.STRING, - number=1, - ) - state: CryptoKeyVersionState = proto.Field( - proto.ENUM, - number=3, - enum=CryptoKeyVersionState, - ) - protection_level: 'ProtectionLevel' = proto.Field( - proto.ENUM, - number=7, - enum='ProtectionLevel', - ) - algorithm: CryptoKeyVersionAlgorithm = proto.Field( - proto.ENUM, - number=10, - enum=CryptoKeyVersionAlgorithm, - ) - attestation: 'KeyOperationAttestation' = proto.Field( - proto.MESSAGE, - number=8, - message='KeyOperationAttestation', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - generate_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=11, - message=timestamp_pb2.Timestamp, - ) - destroy_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - destroy_event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=6, - message=timestamp_pb2.Timestamp, - ) - import_job: str = proto.Field( - proto.STRING, - number=14, - ) - import_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=15, - message=timestamp_pb2.Timestamp, - ) - import_failure_reason: str = proto.Field( - proto.STRING, - number=16, - ) - generation_failure_reason: str = proto.Field( - proto.STRING, - number=19, - ) - external_destruction_failure_reason: str = proto.Field( - proto.STRING, - number=20, - ) - external_protection_level_options: 'ExternalProtectionLevelOptions' = proto.Field( - proto.MESSAGE, - number=17, - message='ExternalProtectionLevelOptions', - ) - reimport_eligible: bool = proto.Field( - proto.BOOL, - number=18, - ) - - -class PublicKey(proto.Message): - r"""The public keys for a given - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Obtained - via - [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - Attributes: - pem (str): - The public key, encoded in PEM format. For more information, - see the `RFC 7468 `__ - sections for `General - Considerations `__ - and [Textual Encoding of Subject Public Key Info] - (https://tools.ietf.org/html/rfc7468#section-13). - algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): - The - [Algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] - associated with this key. - pem_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem]. - An integrity check of - [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem] can be - performed by computing the CRC32C checksum of - [PublicKey.pem][google.cloud.kms.v1.PublicKey.pem] and - comparing your results to this field. Discard the response - in case of non-matching checksum values, and perform a - limited number of retries. A persistent mismatch may - indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - - NOTE: This field is in Beta. - name (str): - The [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - public key. Provided here for verification. - - NOTE: This field is in Beta. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - public key. - """ - - pem: str = proto.Field( - proto.STRING, - number=1, - ) - algorithm: 'CryptoKeyVersion.CryptoKeyVersionAlgorithm' = proto.Field( - proto.ENUM, - number=2, - enum='CryptoKeyVersion.CryptoKeyVersionAlgorithm', - ) - pem_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int64Value, - ) - name: str = proto.Field( - proto.STRING, - number=4, - ) - protection_level: 'ProtectionLevel' = proto.Field( - proto.ENUM, - number=5, - enum='ProtectionLevel', - ) - - -class ImportJob(proto.Message): - r"""An [ImportJob][google.cloud.kms.v1.ImportJob] can be used to create - [CryptoKeys][google.cloud.kms.v1.CryptoKey] and - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] using - pre-existing key material, generated outside of Cloud KMS. - - When an [ImportJob][google.cloud.kms.v1.ImportJob] is created, Cloud - KMS will generate a "wrapping key", which is a public/private key - pair. You use the wrapping key to encrypt (also known as wrap) the - pre-existing key material to protect it during the import process. - The nature of the wrapping key depends on the choice of - [import_method][google.cloud.kms.v1.ImportJob.import_method]. When - the wrapping key generation is complete, the - [state][google.cloud.kms.v1.ImportJob.state] will be set to - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] and - the [public_key][google.cloud.kms.v1.ImportJob.public_key] can be - fetched. The fetched public key can then be used to wrap your - pre-existing key material. - - Once the key material is wrapped, it can be imported into a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in an - existing [CryptoKey][google.cloud.kms.v1.CryptoKey] by calling - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - Multiple [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can be imported with a single - [ImportJob][google.cloud.kms.v1.ImportJob]. Cloud KMS uses the - private key portion of the wrapping key to unwrap the key material. - Only Cloud KMS has access to the private key. - - An [ImportJob][google.cloud.kms.v1.ImportJob] expires 3 days after - it is created. Once expired, Cloud KMS will no longer be able to - import or unwrap any key material that was wrapped with the - [ImportJob][google.cloud.kms.v1.ImportJob]'s public key. - - For more information, see `Importing a - key `__. - - Attributes: - name (str): - Output only. The resource name for this - [ImportJob][google.cloud.kms.v1.ImportJob] in the format - ``projects/*/locations/*/keyRings/*/importJobs/*``. - import_method (google.cloud.kms_v1.types.ImportJob.ImportMethod): - Required. Immutable. The wrapping method to - be used for incoming key material. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - Required. Immutable. The protection level of the - [ImportJob][google.cloud.kms.v1.ImportJob]. This must match - the - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] - of the - [version_template][google.cloud.kms.v1.CryptoKey.version_template] - on the [CryptoKey][google.cloud.kms.v1.CryptoKey] you - attempt to import into. - create_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [ImportJob][google.cloud.kms.v1.ImportJob] was created. - generate_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this - [ImportJob][google.cloud.kms.v1.ImportJob]'s key material - was generated. - expire_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time at which this - [ImportJob][google.cloud.kms.v1.ImportJob] is scheduled for - expiration and can no longer be used to import key material. - expire_event_time (google.protobuf.timestamp_pb2.Timestamp): - Output only. The time this - [ImportJob][google.cloud.kms.v1.ImportJob] expired. Only - present if [state][google.cloud.kms.v1.ImportJob.state] is - [EXPIRED][google.cloud.kms.v1.ImportJob.ImportJobState.EXPIRED]. - state (google.cloud.kms_v1.types.ImportJob.ImportJobState): - Output only. The current state of the - [ImportJob][google.cloud.kms.v1.ImportJob], indicating if it - can be used. - public_key (google.cloud.kms_v1.types.ImportJob.WrappingPublicKey): - Output only. The public key with which to wrap key material - prior to import. Only returned if - [state][google.cloud.kms.v1.ImportJob.state] is - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE]. - attestation (google.cloud.kms_v1.types.KeyOperationAttestation): - Output only. Statement that was generated and signed by the - key creator (for example, an HSM) at key creation time. Use - this statement to verify attributes of the key as stored on - the HSM, independently of Google. Only present if the chosen - [ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod] - is one with a protection level of - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM]. - """ - class ImportMethod(proto.Enum): - r"""[ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod] describes - the key wrapping method chosen for this - [ImportJob][google.cloud.kms.v1.ImportJob]. - - Values: - IMPORT_METHOD_UNSPECIFIED (0): - Not specified. - RSA_OAEP_3072_SHA1_AES_256 (1): - This ImportMethod represents the CKM_RSA_AES_KEY_WRAP key - wrapping scheme defined in the PKCS #11 standard. In - summary, this involves wrapping the raw key with an - ephemeral AES key, and wrapping the ephemeral AES key with a - 3072 bit RSA key. For more details, see `RSA AES key wrap - mechanism `__. - RSA_OAEP_4096_SHA1_AES_256 (2): - This ImportMethod represents the CKM_RSA_AES_KEY_WRAP key - wrapping scheme defined in the PKCS #11 standard. In - summary, this involves wrapping the raw key with an - ephemeral AES key, and wrapping the ephemeral AES key with a - 4096 bit RSA key. For more details, see `RSA AES key wrap - mechanism `__. - RSA_OAEP_3072_SHA256_AES_256 (3): - This ImportMethod represents the CKM_RSA_AES_KEY_WRAP key - wrapping scheme defined in the PKCS #11 standard. In - summary, this involves wrapping the raw key with an - ephemeral AES key, and wrapping the ephemeral AES key with a - 3072 bit RSA key. For more details, see `RSA AES key wrap - mechanism `__. - RSA_OAEP_4096_SHA256_AES_256 (4): - This ImportMethod represents the CKM_RSA_AES_KEY_WRAP key - wrapping scheme defined in the PKCS #11 standard. In - summary, this involves wrapping the raw key with an - ephemeral AES key, and wrapping the ephemeral AES key with a - 4096 bit RSA key. For more details, see `RSA AES key wrap - mechanism `__. - RSA_OAEP_3072_SHA256 (5): - This ImportMethod represents RSAES-OAEP with - a 3072 bit RSA key. The key material to be - imported is wrapped directly with the RSA key. - Due to technical limitations of RSA wrapping, - this method cannot be used to wrap RSA keys for - import. - RSA_OAEP_4096_SHA256 (6): - This ImportMethod represents RSAES-OAEP with - a 4096 bit RSA key. The key material to be - imported is wrapped directly with the RSA key. - Due to technical limitations of RSA wrapping, - this method cannot be used to wrap RSA keys for - import. - """ - IMPORT_METHOD_UNSPECIFIED = 0 - RSA_OAEP_3072_SHA1_AES_256 = 1 - RSA_OAEP_4096_SHA1_AES_256 = 2 - RSA_OAEP_3072_SHA256_AES_256 = 3 - RSA_OAEP_4096_SHA256_AES_256 = 4 - RSA_OAEP_3072_SHA256 = 5 - RSA_OAEP_4096_SHA256 = 6 - - class ImportJobState(proto.Enum): - r"""The state of the [ImportJob][google.cloud.kms.v1.ImportJob], - indicating if it can be used. - - Values: - IMPORT_JOB_STATE_UNSPECIFIED (0): - Not specified. - PENDING_GENERATION (1): - The wrapping key for this job is still being generated. It - may not be used. Cloud KMS will automatically mark this job - as - [ACTIVE][google.cloud.kms.v1.ImportJob.ImportJobState.ACTIVE] - as soon as the wrapping key is generated. - ACTIVE (2): - This job may be used in - [CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey] - and - [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] - requests. - EXPIRED (3): - This job can no longer be used and may not - leave this state once entered. - """ - IMPORT_JOB_STATE_UNSPECIFIED = 0 - PENDING_GENERATION = 1 - ACTIVE = 2 - EXPIRED = 3 - - class WrappingPublicKey(proto.Message): - r"""The public key component of the wrapping key. For details of the - type of key this public key corresponds to, see the - [ImportMethod][google.cloud.kms.v1.ImportJob.ImportMethod]. - - Attributes: - pem (str): - The public key, encoded in PEM format. For more information, - see the `RFC 7468 `__ - sections for `General - Considerations `__ - and [Textual Encoding of Subject Public Key Info] - (https://tools.ietf.org/html/rfc7468#section-13). - """ - - pem: str = proto.Field( - proto.STRING, - number=1, - ) - - name: str = proto.Field( - proto.STRING, - number=1, - ) - import_method: ImportMethod = proto.Field( - proto.ENUM, - number=2, - enum=ImportMethod, - ) - protection_level: 'ProtectionLevel' = proto.Field( - proto.ENUM, - number=9, - enum='ProtectionLevel', - ) - create_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=3, - message=timestamp_pb2.Timestamp, - ) - generate_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=4, - message=timestamp_pb2.Timestamp, - ) - expire_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=5, - message=timestamp_pb2.Timestamp, - ) - expire_event_time: timestamp_pb2.Timestamp = proto.Field( - proto.MESSAGE, - number=10, - message=timestamp_pb2.Timestamp, - ) - state: ImportJobState = proto.Field( - proto.ENUM, - number=6, - enum=ImportJobState, - ) - public_key: WrappingPublicKey = proto.Field( - proto.MESSAGE, - number=7, - message=WrappingPublicKey, - ) - attestation: 'KeyOperationAttestation' = proto.Field( - proto.MESSAGE, - number=8, - message='KeyOperationAttestation', - ) - - -class ExternalProtectionLevelOptions(proto.Message): - r"""ExternalProtectionLevelOptions stores a group of additional fields - for configuring a - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] that are - specific to the - [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] protection - level and - [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] - protection levels. - - Attributes: - external_key_uri (str): - The URI for an external resource that this - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - represents. - ekm_connection_key_path (str): - The path to the external key material on the EKM when using - [EkmConnection][google.cloud.kms.v1.EkmConnection] e.g., - "v0/my/key". Set this field instead of external_key_uri when - using an [EkmConnection][google.cloud.kms.v1.EkmConnection]. - """ - - external_key_uri: str = proto.Field( - proto.STRING, - number=1, - ) - ekm_connection_key_path: str = proto.Field( - proto.STRING, - number=2, - ) - - -class KeyAccessJustificationsPolicy(proto.Message): - r"""A - [KeyAccessJustificationsPolicy][google.cloud.kms.v1.KeyAccessJustificationsPolicy] - specifies zero or more allowed - [AccessReason][google.cloud.kms.v1.AccessReason] values for encrypt, - decrypt, and sign operations on a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - - Attributes: - allowed_access_reasons (MutableSequence[google.cloud.kms_v1.types.AccessReason]): - The list of allowed reasons for access to a - [CryptoKey][google.cloud.kms.v1.CryptoKey]. Zero allowed - access reasons means all encrypt, decrypt, and sign - operations for the - [CryptoKey][google.cloud.kms.v1.CryptoKey] associated with - this policy will fail. - """ - - allowed_access_reasons: MutableSequence['AccessReason'] = proto.RepeatedField( - proto.ENUM, - number=1, - enum='AccessReason', - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/service.py b/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/service.py deleted file mode 100644 index d6e464df2ab9..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/google/cloud/kms_v1/types/service.py +++ /dev/null @@ -1,2528 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -from __future__ import annotations - -from typing import MutableMapping, MutableSequence - -import proto # type: ignore - -from google.cloud.kms_v1.types import resources -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore - - -__protobuf__ = proto.module( - package='google.cloud.kms.v1', - manifest={ - 'ListKeyRingsRequest', - 'ListCryptoKeysRequest', - 'ListCryptoKeyVersionsRequest', - 'ListImportJobsRequest', - 'ListKeyRingsResponse', - 'ListCryptoKeysResponse', - 'ListCryptoKeyVersionsResponse', - 'ListImportJobsResponse', - 'GetKeyRingRequest', - 'GetCryptoKeyRequest', - 'GetCryptoKeyVersionRequest', - 'GetPublicKeyRequest', - 'GetImportJobRequest', - 'CreateKeyRingRequest', - 'CreateCryptoKeyRequest', - 'CreateCryptoKeyVersionRequest', - 'ImportCryptoKeyVersionRequest', - 'CreateImportJobRequest', - 'UpdateCryptoKeyRequest', - 'UpdateCryptoKeyVersionRequest', - 'UpdateCryptoKeyPrimaryVersionRequest', - 'DestroyCryptoKeyVersionRequest', - 'RestoreCryptoKeyVersionRequest', - 'EncryptRequest', - 'DecryptRequest', - 'RawEncryptRequest', - 'RawDecryptRequest', - 'AsymmetricSignRequest', - 'AsymmetricDecryptRequest', - 'MacSignRequest', - 'MacVerifyRequest', - 'GenerateRandomBytesRequest', - 'EncryptResponse', - 'DecryptResponse', - 'RawEncryptResponse', - 'RawDecryptResponse', - 'AsymmetricSignResponse', - 'AsymmetricDecryptResponse', - 'MacSignResponse', - 'MacVerifyResponse', - 'GenerateRandomBytesResponse', - 'Digest', - 'LocationMetadata', - }, -) - - -class ListKeyRingsRequest(proto.Message): - r"""Request message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - - Attributes: - parent (str): - Required. The resource name of the location associated with - the [KeyRings][google.cloud.kms.v1.KeyRing], in the format - ``projects/*/locations/*``. - page_size (int): - Optional. Optional limit on the number of - [KeyRings][google.cloud.kms.v1.KeyRing] to include in the - response. Further [KeyRings][google.cloud.kms.v1.KeyRing] - can subsequently be obtained by including the - [ListKeyRingsResponse.next_page_token][google.cloud.kms.v1.ListKeyRingsResponse.next_page_token] - in a subsequent request. If unspecified, the server will - pick an appropriate default. - page_token (str): - Optional. Optional pagination token, returned earlier via - [ListKeyRingsResponse.next_page_token][google.cloud.kms.v1.ListKeyRingsResponse.next_page_token]. - filter (str): - Optional. Only include resources that match the filter in - the response. For more information, see `Sorting and - filtering list - results `__. - order_by (str): - Optional. Specify how the results should be sorted. If not - specified, the results will be sorted in the default order. - For more information, see `Sorting and filtering list - results `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListCryptoKeysRequest(proto.Message): - r"""Request message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - - Attributes: - parent (str): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - page_size (int): - Optional. Optional limit on the number of - [CryptoKeys][google.cloud.kms.v1.CryptoKey] to include in - the response. Further - [CryptoKeys][google.cloud.kms.v1.CryptoKey] can subsequently - be obtained by including the - [ListCryptoKeysResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token] - in a subsequent request. If unspecified, the server will - pick an appropriate default. - page_token (str): - Optional. Optional pagination token, returned earlier via - [ListCryptoKeysResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeysResponse.next_page_token]. - version_view (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionView): - The fields of the primary version to include - in the response. - filter (str): - Optional. Only include resources that match the filter in - the response. For more information, see `Sorting and - filtering list - results `__. - order_by (str): - Optional. Specify how the results should be sorted. If not - specified, the results will be sorted in the default order. - For more information, see `Sorting and filtering list - results `__. - """ - - 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, - ) - version_view: resources.CryptoKeyVersion.CryptoKeyVersionView = proto.Field( - proto.ENUM, - number=4, - enum=resources.CryptoKeyVersion.CryptoKeyVersionView, - ) - filter: str = proto.Field( - proto.STRING, - number=5, - ) - order_by: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ListCryptoKeyVersionsRequest(proto.Message): - r"""Request message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - - Attributes: - parent (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to list, in the - format ``projects/*/locations/*/keyRings/*/cryptoKeys/*``. - page_size (int): - Optional. Optional limit on the number of - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] to - include in the response. Further - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - can subsequently be obtained by including the - [ListCryptoKeyVersionsResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token] - in a subsequent request. If unspecified, the server will - pick an appropriate default. - page_token (str): - Optional. Optional pagination token, returned earlier via - [ListCryptoKeyVersionsResponse.next_page_token][google.cloud.kms.v1.ListCryptoKeyVersionsResponse.next_page_token]. - view (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionView): - The fields to include in the response. - filter (str): - Optional. Only include resources that match the filter in - the response. For more information, see `Sorting and - filtering list - results `__. - order_by (str): - Optional. Specify how the results should be sorted. If not - specified, the results will be sorted in the default order. - For more information, see `Sorting and filtering list - results `__. - """ - - 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, - ) - view: resources.CryptoKeyVersion.CryptoKeyVersionView = proto.Field( - proto.ENUM, - number=4, - enum=resources.CryptoKeyVersion.CryptoKeyVersionView, - ) - filter: str = proto.Field( - proto.STRING, - number=5, - ) - order_by: str = proto.Field( - proto.STRING, - number=6, - ) - - -class ListImportJobsRequest(proto.Message): - r"""Request message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - - Attributes: - parent (str): - Required. The resource name of the - [KeyRing][google.cloud.kms.v1.KeyRing] to list, in the - format ``projects/*/locations/*/keyRings/*``. - page_size (int): - Optional. Optional limit on the number of - [ImportJobs][google.cloud.kms.v1.ImportJob] to include in - the response. Further - [ImportJobs][google.cloud.kms.v1.ImportJob] can subsequently - be obtained by including the - [ListImportJobsResponse.next_page_token][google.cloud.kms.v1.ListImportJobsResponse.next_page_token] - in a subsequent request. If unspecified, the server will - pick an appropriate default. - page_token (str): - Optional. Optional pagination token, returned earlier via - [ListImportJobsResponse.next_page_token][google.cloud.kms.v1.ListImportJobsResponse.next_page_token]. - filter (str): - Optional. Only include resources that match the filter in - the response. For more information, see `Sorting and - filtering list - results `__. - order_by (str): - Optional. Specify how the results should be sorted. If not - specified, the results will be sorted in the default order. - For more information, see `Sorting and filtering list - results `__. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - page_size: int = proto.Field( - proto.INT32, - number=2, - ) - page_token: str = proto.Field( - proto.STRING, - number=3, - ) - filter: str = proto.Field( - proto.STRING, - number=4, - ) - order_by: str = proto.Field( - proto.STRING, - number=5, - ) - - -class ListKeyRingsResponse(proto.Message): - r"""Response message for - [KeyManagementService.ListKeyRings][google.cloud.kms.v1.KeyManagementService.ListKeyRings]. - - Attributes: - key_rings (MutableSequence[google.cloud.kms_v1.types.KeyRing]): - The list of [KeyRings][google.cloud.kms.v1.KeyRing]. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - [ListKeyRingsRequest.page_token][google.cloud.kms.v1.ListKeyRingsRequest.page_token] - to retrieve the next page of results. - total_size (int): - The total number of [KeyRings][google.cloud.kms.v1.KeyRing] - that matched the query. - """ - - @property - def raw_page(self): - return self - - key_rings: MutableSequence[resources.KeyRing] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.KeyRing, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListCryptoKeysResponse(proto.Message): - r"""Response message for - [KeyManagementService.ListCryptoKeys][google.cloud.kms.v1.KeyManagementService.ListCryptoKeys]. - - Attributes: - crypto_keys (MutableSequence[google.cloud.kms_v1.types.CryptoKey]): - The list of [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - [ListCryptoKeysRequest.page_token][google.cloud.kms.v1.ListCryptoKeysRequest.page_token] - to retrieve the next page of results. - total_size (int): - The total number of - [CryptoKeys][google.cloud.kms.v1.CryptoKey] that matched the - query. - """ - - @property - def raw_page(self): - return self - - crypto_keys: MutableSequence[resources.CryptoKey] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.CryptoKey, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListCryptoKeyVersionsResponse(proto.Message): - r"""Response message for - [KeyManagementService.ListCryptoKeyVersions][google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions]. - - Attributes: - crypto_key_versions (MutableSequence[google.cloud.kms_v1.types.CryptoKeyVersion]): - The list of - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - [ListCryptoKeyVersionsRequest.page_token][google.cloud.kms.v1.ListCryptoKeyVersionsRequest.page_token] - to retrieve the next page of results. - total_size (int): - The total number of - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] - that matched the query. - """ - - @property - def raw_page(self): - return self - - crypto_key_versions: MutableSequence[resources.CryptoKeyVersion] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.CryptoKeyVersion, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class ListImportJobsResponse(proto.Message): - r"""Response message for - [KeyManagementService.ListImportJobs][google.cloud.kms.v1.KeyManagementService.ListImportJobs]. - - Attributes: - import_jobs (MutableSequence[google.cloud.kms_v1.types.ImportJob]): - The list of [ImportJobs][google.cloud.kms.v1.ImportJob]. - next_page_token (str): - A token to retrieve next page of results. Pass this value in - [ListImportJobsRequest.page_token][google.cloud.kms.v1.ListImportJobsRequest.page_token] - to retrieve the next page of results. - total_size (int): - The total number of - [ImportJobs][google.cloud.kms.v1.ImportJob] that matched the - query. - """ - - @property - def raw_page(self): - return self - - import_jobs: MutableSequence[resources.ImportJob] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=resources.ImportJob, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - total_size: int = proto.Field( - proto.INT32, - number=3, - ) - - -class GetKeyRingRequest(proto.Message): - r"""Request message for - [KeyManagementService.GetKeyRing][google.cloud.kms.v1.KeyManagementService.GetKeyRing]. - - Attributes: - name (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] of - the [KeyRing][google.cloud.kms.v1.KeyRing] to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetCryptoKeyRequest(proto.Message): - r"""Request message for - [KeyManagementService.GetCryptoKey][google.cloud.kms.v1.KeyManagementService.GetCryptoKey]. - - Attributes: - name (str): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] of - the [CryptoKey][google.cloud.kms.v1.CryptoKey] to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.GetCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion]. - - Attributes: - name (str): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetPublicKeyRequest(proto.Message): - r"""Request message for - [KeyManagementService.GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. - - Attributes: - name (str): - Required. The - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - public key to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class GetImportJobRequest(proto.Message): - r"""Request message for - [KeyManagementService.GetImportJob][google.cloud.kms.v1.KeyManagementService.GetImportJob]. - - Attributes: - name (str): - Required. The [name][google.cloud.kms.v1.ImportJob.name] of - the [ImportJob][google.cloud.kms.v1.ImportJob] to get. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class CreateKeyRingRequest(proto.Message): - r"""Request message for - [KeyManagementService.CreateKeyRing][google.cloud.kms.v1.KeyManagementService.CreateKeyRing]. - - Attributes: - parent (str): - Required. The resource name of the location associated with - the [KeyRings][google.cloud.kms.v1.KeyRing], in the format - ``projects/*/locations/*``. - key_ring_id (str): - Required. It must be unique within a location and match the - regular expression ``[a-zA-Z0-9_-]{1,63}`` - key_ring (google.cloud.kms_v1.types.KeyRing): - Required. A [KeyRing][google.cloud.kms.v1.KeyRing] with - initial field values. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - key_ring_id: str = proto.Field( - proto.STRING, - number=2, - ) - key_ring: resources.KeyRing = proto.Field( - proto.MESSAGE, - number=3, - message=resources.KeyRing, - ) - - -class CreateCryptoKeyRequest(proto.Message): - r"""Request message for - [KeyManagementService.CreateCryptoKey][google.cloud.kms.v1.KeyManagementService.CreateCryptoKey]. - - Attributes: - parent (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] of - the KeyRing associated with the - [CryptoKeys][google.cloud.kms.v1.CryptoKey]. - crypto_key_id (str): - Required. It must be unique within a KeyRing and match the - regular expression ``[a-zA-Z0-9_-]{1,63}`` - crypto_key (google.cloud.kms_v1.types.CryptoKey): - Required. A [CryptoKey][google.cloud.kms.v1.CryptoKey] with - initial field values. - skip_initial_version_creation (bool): - If set to true, the request will create a - [CryptoKey][google.cloud.kms.v1.CryptoKey] without any - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - You must manually call - [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion] - or - [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion] - before you can use this - [CryptoKey][google.cloud.kms.v1.CryptoKey]. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - crypto_key_id: str = proto.Field( - proto.STRING, - number=2, - ) - crypto_key: resources.CryptoKey = proto.Field( - proto.MESSAGE, - number=3, - message=resources.CryptoKey, - ) - skip_initial_version_creation: bool = proto.Field( - proto.BOOL, - number=5, - ) - - -class CreateCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion]. - - Attributes: - parent (str): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] of - the [CryptoKey][google.cloud.kms.v1.CryptoKey] associated - with the - [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion]. - crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): - Required. A - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with initial field values. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - crypto_key_version: resources.CryptoKeyVersion = proto.Field( - proto.MESSAGE, - number=2, - message=resources.CryptoKeyVersion, - ) - - -class ImportCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - parent (str): - Required. The [name][google.cloud.kms.v1.CryptoKey.name] of - the [CryptoKey][google.cloud.kms.v1.CryptoKey] to be - imported into. - - The create permission is only required on this key when - creating a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. - crypto_key_version (str): - Optional. The optional - [name][google.cloud.kms.v1.CryptoKeyVersion.name] of an - existing - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - target for an import operation. If this field is not - present, a new - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - containing the supplied key material is created. - - If this field is present, the supplied key material is - imported into the existing - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. To - import into an existing - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], - the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - must be a child of - [ImportCryptoKeyVersionRequest.parent][google.cloud.kms.v1.ImportCryptoKeyVersionRequest.parent], - have been previously created via [ImportCryptoKeyVersion][], - and be in - [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED] - or - [IMPORT_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.IMPORT_FAILED] - state. The key material and algorithm must match the - previous - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - exactly if the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] has - ever contained key material. - algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): - Required. The - [algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] - of the key being imported. This does not need to match the - [version_template][google.cloud.kms.v1.CryptoKey.version_template] - of the [CryptoKey][google.cloud.kms.v1.CryptoKey] this - version imports into. - import_job (str): - Required. The [name][google.cloud.kms.v1.ImportJob.name] of - the [ImportJob][google.cloud.kms.v1.ImportJob] that was used - to wrap this key material. - wrapped_key (bytes): - Optional. The wrapped key material to import. - - Before wrapping, key material must be formatted. If - importing symmetric key material, the expected key material - format is plain bytes. If importing asymmetric key material, - the expected key material format is PKCS#8-encoded DER (the - PrivateKeyInfo structure from RFC 5208). - - When wrapping with import methods - ([RSA_OAEP_3072_SHA1_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256] - or - [RSA_OAEP_4096_SHA1_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA1_AES_256] - or - [RSA_OAEP_3072_SHA256_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA256_AES_256] - or - [RSA_OAEP_4096_SHA256_AES_256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA256_AES_256]), - - this field must contain the concatenation of: - - .. raw:: html - -
    -
  1. An ephemeral AES-256 wrapping key wrapped with the - [public_key][google.cloud.kms.v1.ImportJob.public_key] using - RSAES-OAEP with SHA-1/SHA-256, MGF1 with SHA-1/SHA-256, and an empty - label. -
  2. -
  3. The formatted key to be imported, wrapped with the ephemeral AES-256 - key using AES-KWP (RFC 5649). -
  4. -
- - This format is the same as the format produced by PKCS#11 - mechanism CKM_RSA_AES_KEY_WRAP. - - When wrapping with import methods - ([RSA_OAEP_3072_SHA256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_3072_SHA256] - or - [RSA_OAEP_4096_SHA256][google.cloud.kms.v1.ImportJob.ImportMethod.RSA_OAEP_4096_SHA256]), - - this field must contain the formatted key to be imported, - wrapped with the - [public_key][google.cloud.kms.v1.ImportJob.public_key] using - RSAES-OAEP with SHA-256, MGF1 with SHA-256, and an empty - label. - rsa_aes_wrapped_key (bytes): - Optional. This field has the same meaning as - [wrapped_key][google.cloud.kms.v1.ImportCryptoKeyVersionRequest.wrapped_key]. - Prefer to use that field in new work. Either that field or - this field (but not both) must be specified. - - This field is a member of `oneof`_ ``wrapped_key_material``. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - crypto_key_version: str = proto.Field( - proto.STRING, - number=6, - ) - algorithm: resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm = proto.Field( - proto.ENUM, - number=2, - enum=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm, - ) - import_job: str = proto.Field( - proto.STRING, - number=4, - ) - wrapped_key: bytes = proto.Field( - proto.BYTES, - number=8, - ) - rsa_aes_wrapped_key: bytes = proto.Field( - proto.BYTES, - number=5, - oneof='wrapped_key_material', - ) - - -class CreateImportJobRequest(proto.Message): - r"""Request message for - [KeyManagementService.CreateImportJob][google.cloud.kms.v1.KeyManagementService.CreateImportJob]. - - Attributes: - parent (str): - Required. The [name][google.cloud.kms.v1.KeyRing.name] of - the [KeyRing][google.cloud.kms.v1.KeyRing] associated with - the [ImportJobs][google.cloud.kms.v1.ImportJob]. - import_job_id (str): - Required. It must be unique within a KeyRing and match the - regular expression ``[a-zA-Z0-9_-]{1,63}`` - import_job (google.cloud.kms_v1.types.ImportJob): - Required. An [ImportJob][google.cloud.kms.v1.ImportJob] with - initial field values. - """ - - parent: str = proto.Field( - proto.STRING, - number=1, - ) - import_job_id: str = proto.Field( - proto.STRING, - number=2, - ) - import_job: resources.ImportJob = proto.Field( - proto.MESSAGE, - number=3, - message=resources.ImportJob, - ) - - -class UpdateCryptoKeyRequest(proto.Message): - r"""Request message for - [KeyManagementService.UpdateCryptoKey][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey]. - - Attributes: - crypto_key (google.cloud.kms_v1.types.CryptoKey): - Required. [CryptoKey][google.cloud.kms.v1.CryptoKey] with - updated values. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - crypto_key: resources.CryptoKey = proto.Field( - proto.MESSAGE, - number=1, - message=resources.CryptoKey, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.UpdateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion]. - - Attributes: - crypto_key_version (google.cloud.kms_v1.types.CryptoKeyVersion): - Required. - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - with updated values. - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. List of fields to be updated in - this request. - """ - - crypto_key_version: resources.CryptoKeyVersion = proto.Field( - proto.MESSAGE, - number=1, - message=resources.CryptoKeyVersion, - ) - update_mask: field_mask_pb2.FieldMask = proto.Field( - proto.MESSAGE, - number=2, - message=field_mask_pb2.FieldMask, - ) - - -class UpdateCryptoKeyPrimaryVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.UpdateCryptoKeyPrimaryVersion][google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to update. - crypto_key_version_id (str): - Required. The id of the child - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use as primary. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - crypto_key_version_id: str = proto.Field( - proto.STRING, - number=2, - ) - - -class DestroyCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - destroy. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class RestoreCryptoKeyVersionRequest(proto.Message): - r"""Request message for - [KeyManagementService.RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - restore. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - - -class EncryptRequest(proto.Message): - r"""Request message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] or - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for encryption. - - If a [CryptoKey][google.cloud.kms.v1.CryptoKey] is - specified, the server will use its [primary - version][google.cloud.kms.v1.CryptoKey.primary]. - plaintext (bytes): - Required. The data to encrypt. Must be no larger than 64KiB. - - The maximum size depends on the key version's - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. - For - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE], - [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL], - and - [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] - keys, the plaintext must be no larger than 64KiB. For - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the - combined length of the plaintext and - additional_authenticated_data fields must be no larger than - 8KiB. - additional_authenticated_data (bytes): - Optional. Optional data that, if specified, must also be - provided during decryption through - [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]. - - The maximum size depends on the key version's - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. - For - [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE], - [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL], - and - [EXTERNAL_VPC][google.cloud.kms.v1.ProtectionLevel.EXTERNAL_VPC] - keys the AAD must be no larger than 64KiB. For - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the - combined length of the plaintext and - additional_authenticated_data fields must be no larger than - 8KiB. - plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]) - is equal to - [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]) - is equal to - [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - plaintext: bytes = proto.Field( - proto.BYTES, - number=2, - ) - additional_authenticated_data: bytes = proto.Field( - proto.BYTES, - number=3, - ) - plaintext_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=7, - message=wrappers_pb2.Int64Value, - ) - additional_authenticated_data_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=8, - message=wrappers_pb2.Int64Value, - ) - - -class DecryptRequest(proto.Message): - r"""Request message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKey][google.cloud.kms.v1.CryptoKey] to use for - decryption. The server will choose the appropriate version. - ciphertext (bytes): - Required. The encrypted data originally returned in - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. - additional_authenticated_data (bytes): - Optional. Optional data that must match the data originally - supplied in - [EncryptRequest.additional_authenticated_data][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. - ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([DecryptRequest.ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]) - is equal to - [DecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.DecryptRequest.ciphertext_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([DecryptRequest.additional_authenticated_data][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data]) - is equal to - [DecryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.DecryptRequest.additional_authenticated_data_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - ciphertext: bytes = proto.Field( - proto.BYTES, - number=2, - ) - additional_authenticated_data: bytes = proto.Field( - proto.BYTES, - number=3, - ) - ciphertext_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.Int64Value, - ) - additional_authenticated_data_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.Int64Value, - ) - - -class RawEncryptRequest(proto.Message): - r"""Request message for - [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for encryption. - plaintext (bytes): - Required. The data to encrypt. Must be no larger than 64KiB. - - The maximum size depends on the key version's - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. - For [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] - keys, the plaintext must be no larger than 64KiB. For - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the - combined length of the plaintext and - additional_authenticated_data fields must be no larger than - 8KiB. - additional_authenticated_data (bytes): - Optional. Optional data that, if specified, must also be - provided during decryption through - [RawDecryptRequest.additional_authenticated_data][google.cloud.kms.v1.RawDecryptRequest.additional_authenticated_data]. - - This field may only be used in conjunction with an - [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm] - that accepts additional authenticated data (for example, - AES-GCM). - - The maximum size depends on the key version's - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level]. - For [SOFTWARE][google.cloud.kms.v1.ProtectionLevel.SOFTWARE] - keys, the plaintext must be no larger than 64KiB. For - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] keys, the - combined length of the plaintext and - additional_authenticated_data fields must be no larger than - 8KiB. - plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [RawEncryptRequest.plaintext][google.cloud.kms.v1.RawEncryptRequest.plaintext]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received plaintext using - this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C(plaintext) is equal to plaintext_crc32c, and if so, - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [RawEncryptRequest.additional_authenticated_data][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - additional_authenticated_data using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C(additional_authenticated_data) is equal to - additional_authenticated_data_crc32c, and if so, perform a - limited number of retries. A persistent mismatch may - indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - initialization_vector (bytes): - Optional. A customer-supplied initialization vector that - will be used for encryption. If it is not provided for - AES-CBC and AES-CTR, one will be generated. It will be - returned in - [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector]. - initialization_vector_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [RawEncryptRequest.initialization_vector][google.cloud.kms.v1.RawEncryptRequest.initialization_vector]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - initialization_vector using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C(initialization_vector) is equal to - initialization_vector_crc32c, and if so, perform a limited - number of retries. A persistent mismatch may indicate an - issue in your computation of the CRC32C checksum. Note: This - field is defined as int64 for reasons of compatibility - across different languages. However, it is a non-negative - integer, which will never exceed 2^32-1, and can be safely - downconverted to uint32 in languages that support this type. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - plaintext: bytes = proto.Field( - proto.BYTES, - number=2, - ) - additional_authenticated_data: bytes = proto.Field( - proto.BYTES, - number=3, - ) - plaintext_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=4, - message=wrappers_pb2.Int64Value, - ) - additional_authenticated_data_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.Int64Value, - ) - initialization_vector: bytes = proto.Field( - proto.BYTES, - number=6, - ) - initialization_vector_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=7, - message=wrappers_pb2.Int64Value, - ) - - -class RawDecryptRequest(proto.Message): - r"""Request message for - [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for decryption. - ciphertext (bytes): - Required. The encrypted data originally returned in - [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext]. - additional_authenticated_data (bytes): - Optional. Optional data that must match the data originally - supplied in - [RawEncryptRequest.additional_authenticated_data][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data]. - initialization_vector (bytes): - Required. The initialization vector (IV) used during - encryption, which must match the data originally provided in - [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector]. - tag_length (int): - The length of the authentication tag that is - appended to the end of the ciphertext. If - unspecified (0), the default value for the key's - algorithm will be used (for AES-GCM, the default - value is 16). - ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [RawDecryptRequest.ciphertext][google.cloud.kms.v1.RawDecryptRequest.ciphertext]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received ciphertext using - this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C(ciphertext) is equal to ciphertext_crc32c, and if so, - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - additional_authenticated_data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [RawDecryptRequest.additional_authenticated_data][google.cloud.kms.v1.RawDecryptRequest.additional_authenticated_data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - additional_authenticated_data using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C(additional_authenticated_data) is equal to - additional_authenticated_data_crc32c, and if so, perform a - limited number of retries. A persistent mismatch may - indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - initialization_vector_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [RawDecryptRequest.initialization_vector][google.cloud.kms.v1.RawDecryptRequest.initialization_vector]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - initialization_vector using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C(initialization_vector) is equal to - initialization_vector_crc32c, and if so, perform a limited - number of retries. A persistent mismatch may indicate an - issue in your computation of the CRC32C checksum. Note: This - field is defined as int64 for reasons of compatibility - across different languages. However, it is a non-negative - integer, which will never exceed 2^32-1, and can be safely - downconverted to uint32 in languages that support this type. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - ciphertext: bytes = proto.Field( - proto.BYTES, - number=2, - ) - additional_authenticated_data: bytes = proto.Field( - proto.BYTES, - number=3, - ) - initialization_vector: bytes = proto.Field( - proto.BYTES, - number=4, - ) - tag_length: int = proto.Field( - proto.INT32, - number=5, - ) - ciphertext_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=6, - message=wrappers_pb2.Int64Value, - ) - additional_authenticated_data_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=7, - message=wrappers_pb2.Int64Value, - ) - initialization_vector_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=8, - message=wrappers_pb2.Int64Value, - ) - - -class AsymmetricSignRequest(proto.Message): - r"""Request message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for signing. - digest (google.cloud.kms_v1.types.Digest): - Optional. The digest of the data to sign. The digest must be - produced with the same digest algorithm as specified by the - key version's - [algorithm][google.cloud.kms.v1.CryptoKeyVersion.algorithm]. - - This field may not be supplied if - [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] - is supplied. - digest_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]) - is equal to - [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - data (bytes): - Optional. The data to sign. It can't be supplied if - [AsymmetricSignRequest.digest][google.cloud.kms.v1.AsymmetricSignRequest.digest] - is supplied. - data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([AsymmetricSignRequest.data][google.cloud.kms.v1.AsymmetricSignRequest.data]) - is equal to - [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - digest: 'Digest' = proto.Field( - proto.MESSAGE, - number=3, - message='Digest', - ) - digest_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=4, - message=wrappers_pb2.Int64Value, - ) - data: bytes = proto.Field( - proto.BYTES, - number=6, - ) - data_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=7, - message=wrappers_pb2.Int64Value, - ) - - -class AsymmetricDecryptRequest(proto.Message): - r"""Request message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for decryption. - ciphertext (bytes): - Required. The data encrypted with the named - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s - public key using OAEP. - ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([AsymmetricDecryptRequest.ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]) - is equal to - [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - ciphertext: bytes = proto.Field( - proto.BYTES, - number=3, - ) - ciphertext_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=4, - message=wrappers_pb2.Int64Value, - ) - - -class MacSignRequest(proto.Message): - r"""Request message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for signing. - data (bytes): - Required. The data to sign. The MAC tag is - computed over this data field based on the - specific algorithm. - data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data]) - is equal to - [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - data: bytes = proto.Field( - proto.BYTES, - number=2, - ) - data_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int64Value, - ) - - -class MacVerifyRequest(proto.Message): - r"""Request message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - - Attributes: - name (str): - Required. The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to - use for verification. - data (bytes): - Required. The data used previously as a - [MacSignRequest.data][google.cloud.kms.v1.MacSignRequest.data] - to generate the MAC tag. - data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data]) - is equal to - [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - mac (bytes): - Required. The signature to verify. - mac_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Optional. An optional CRC32C checksum of the - [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac]. - If specified, - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will verify the integrity of the received - [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac] - using this checksum. - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - will report an error if the checksum verification fails. If - you receive a checksum error, your client should verify that - CRC32C([MacVerifyRequest.tag][]) is equal to - [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c], - and if so, perform a limited number of retries. A persistent - mismatch may indicate an issue in your computation of the - CRC32C checksum. Note: This field is defined as int64 for - reasons of compatibility across different languages. - However, it is a non-negative integer, which will never - exceed 2^32-1, and can be safely downconverted to uint32 in - languages that support this type. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - data: bytes = proto.Field( - proto.BYTES, - number=2, - ) - data_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int64Value, - ) - mac: bytes = proto.Field( - proto.BYTES, - number=4, - ) - mac_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.Int64Value, - ) - - -class GenerateRandomBytesRequest(proto.Message): - r"""Request message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - - Attributes: - location (str): - The project-specific location in which to - generate random bytes. For example, - "projects/my-project/locations/us-central1". - length_bytes (int): - The length in bytes of the amount of - randomness to retrieve. Minimum 8 bytes, - maximum 1024 bytes. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - to use when generating the random data. Currently, only - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] protection - level is supported. - """ - - location: str = proto.Field( - proto.STRING, - number=1, - ) - length_bytes: int = proto.Field( - proto.INT32, - number=2, - ) - protection_level: resources.ProtectionLevel = proto.Field( - proto.ENUM, - number=3, - enum=resources.ProtectionLevel, - ) - - -class EncryptResponse(proto.Message): - r"""Response message for - [KeyManagementService.Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. - - Attributes: - name (str): - The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used in encryption. Check this field to verify that the - intended resource was used for encryption. - ciphertext (bytes): - The encrypted data. - ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext]. - An integrity check of - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext] - can be performed by computing the CRC32C checksum of - [EncryptResponse.ciphertext][google.cloud.kms.v1.EncryptResponse.ciphertext] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - verified_plaintext_crc32c (bool): - Integrity verification field. A flag indicating whether - [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. A - false value of this field indicates either that - [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [EncryptRequest.plaintext_crc32c][google.cloud.kms.v1.EncryptRequest.plaintext_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - verified_additional_authenticated_data_crc32c (bool): - Integrity verification field. A flag indicating whether - [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [AAD][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data]. - A false value of this field indicates either that - [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [EncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.EncryptRequest.additional_authenticated_data_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used in encryption. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - ciphertext: bytes = proto.Field( - proto.BYTES, - number=2, - ) - ciphertext_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=4, - message=wrappers_pb2.Int64Value, - ) - verified_plaintext_crc32c: bool = proto.Field( - proto.BOOL, - number=5, - ) - verified_additional_authenticated_data_crc32c: bool = proto.Field( - proto.BOOL, - number=6, - ) - protection_level: resources.ProtectionLevel = proto.Field( - proto.ENUM, - number=7, - enum=resources.ProtectionLevel, - ) - - -class DecryptResponse(proto.Message): - r"""Response message for - [KeyManagementService.Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. - - Attributes: - plaintext (bytes): - The decrypted data originally supplied in - [EncryptRequest.plaintext][google.cloud.kms.v1.EncryptRequest.plaintext]. - plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext]. - An integrity check of - [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext] - can be performed by computing the CRC32C checksum of - [DecryptResponse.plaintext][google.cloud.kms.v1.DecryptResponse.plaintext] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: receiving this response message indicates - that - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - is able to successfully decrypt the - [ciphertext][google.cloud.kms.v1.DecryptRequest.ciphertext]. - Note: This field is defined as int64 for reasons of - compatibility across different languages. However, it is a - non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - used_primary (bool): - Whether the Decryption was performed using - the primary key version. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used in decryption. - """ - - plaintext: bytes = proto.Field( - proto.BYTES, - number=1, - ) - plaintext_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int64Value, - ) - used_primary: bool = proto.Field( - proto.BOOL, - number=3, - ) - protection_level: resources.ProtectionLevel = proto.Field( - proto.ENUM, - number=4, - enum=resources.ProtectionLevel, - ) - - -class RawEncryptResponse(proto.Message): - r"""Response message for - [KeyManagementService.RawEncrypt][google.cloud.kms.v1.KeyManagementService.RawEncrypt]. - - Attributes: - ciphertext (bytes): - The encrypted data. In the case of AES-GCM, the - authentication tag is the - [tag_length][google.cloud.kms.v1.RawEncryptResponse.tag_length] - bytes at the end of this field. - initialization_vector (bytes): - The initialization vector (IV) generated by the service - during encryption. This value must be stored and provided in - [RawDecryptRequest.initialization_vector][google.cloud.kms.v1.RawDecryptRequest.initialization_vector] - at decryption time. - tag_length (int): - The length of the authentication tag that is - appended to the end of the ciphertext. - ciphertext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [RawEncryptResponse.ciphertext][google.cloud.kms.v1.RawEncryptResponse.ciphertext]. - An integrity check of ciphertext can be performed by - computing the CRC32C checksum of ciphertext and comparing - your results to this field. Discard the response in case of - non-matching checksum values, and perform a limited number - of retries. A persistent mismatch may indicate an issue in - your computation of the CRC32C checksum. Note: This field is - defined as int64 for reasons of compatibility across - different languages. However, it is a non-negative integer, - which will never exceed 2^32-1, and can be safely - downconverted to uint32 in languages that support this type. - initialization_vector_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [RawEncryptResponse.initialization_vector][google.cloud.kms.v1.RawEncryptResponse.initialization_vector]. - An integrity check of initialization_vector can be performed - by computing the CRC32C checksum of initialization_vector - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - verified_plaintext_crc32c (bool): - Integrity verification field. A flag indicating whether - [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the plaintext. A - false value of this field indicates either that - [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [RawEncryptRequest.plaintext_crc32c][google.cloud.kms.v1.RawEncryptRequest.plaintext_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - verified_additional_authenticated_data_crc32c (bool): - Integrity verification field. A flag indicating whether - [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of - additional_authenticated_data. A false value of this field - indicates either that // - [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [RawEncryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawEncryptRequest.additional_authenticated_data_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - verified_initialization_vector_crc32c (bool): - Integrity verification field. A flag indicating whether - [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of - initialization_vector. A false value of this field indicates - either that - [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [RawEncryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawEncryptRequest.initialization_vector_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - name (str): - The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used in encryption. Check this field to verify that the - intended resource was used for encryption. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used in encryption. - """ - - ciphertext: bytes = proto.Field( - proto.BYTES, - number=1, - ) - initialization_vector: bytes = proto.Field( - proto.BYTES, - number=2, - ) - tag_length: int = proto.Field( - proto.INT32, - number=3, - ) - ciphertext_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=4, - message=wrappers_pb2.Int64Value, - ) - initialization_vector_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=5, - message=wrappers_pb2.Int64Value, - ) - verified_plaintext_crc32c: bool = proto.Field( - proto.BOOL, - number=6, - ) - verified_additional_authenticated_data_crc32c: bool = proto.Field( - proto.BOOL, - number=7, - ) - verified_initialization_vector_crc32c: bool = proto.Field( - proto.BOOL, - number=10, - ) - name: str = proto.Field( - proto.STRING, - number=8, - ) - protection_level: resources.ProtectionLevel = proto.Field( - proto.ENUM, - number=9, - enum=resources.ProtectionLevel, - ) - - -class RawDecryptResponse(proto.Message): - r"""Response message for - [KeyManagementService.RawDecrypt][google.cloud.kms.v1.KeyManagementService.RawDecrypt]. - - Attributes: - plaintext (bytes): - The decrypted data. - plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [RawDecryptResponse.plaintext][google.cloud.kms.v1.RawDecryptResponse.plaintext]. - An integrity check of plaintext can be performed by - computing the CRC32C checksum of plaintext and comparing - your results to this field. Discard the response in case of - non-matching checksum values, and perform a limited number - of retries. A persistent mismatch may indicate an issue in - your computation of the CRC32C checksum. Note: receiving - this response message indicates that - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - is able to successfully decrypt the - [ciphertext][google.cloud.kms.v1.RawDecryptRequest.ciphertext]. - Note: This field is defined as int64 for reasons of - compatibility across different languages. However, it is a - non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used in decryption. - verified_ciphertext_crc32c (bool): - Integrity verification field. A flag indicating whether - [RawDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.RawDecryptRequest.ciphertext_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the ciphertext. A - false value of this field indicates either that - [RawDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.RawDecryptRequest.ciphertext_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [RawDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.RawDecryptRequest.ciphertext_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - verified_additional_authenticated_data_crc32c (bool): - Integrity verification field. A flag indicating whether - [RawDecryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawDecryptRequest.additional_authenticated_data_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of - additional_authenticated_data. A false value of this field - indicates either that // - [RawDecryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawDecryptRequest.additional_authenticated_data_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [RawDecryptRequest.additional_authenticated_data_crc32c][google.cloud.kms.v1.RawDecryptRequest.additional_authenticated_data_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - verified_initialization_vector_crc32c (bool): - Integrity verification field. A flag indicating whether - [RawDecryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawDecryptRequest.initialization_vector_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of - initialization_vector. A false value of this field indicates - either that - [RawDecryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawDecryptRequest.initialization_vector_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [RawDecryptRequest.initialization_vector_crc32c][google.cloud.kms.v1.RawDecryptRequest.initialization_vector_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - """ - - plaintext: bytes = proto.Field( - proto.BYTES, - number=1, - ) - plaintext_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int64Value, - ) - protection_level: resources.ProtectionLevel = proto.Field( - proto.ENUM, - number=3, - enum=resources.ProtectionLevel, - ) - verified_ciphertext_crc32c: bool = proto.Field( - proto.BOOL, - number=4, - ) - verified_additional_authenticated_data_crc32c: bool = proto.Field( - proto.BOOL, - number=5, - ) - verified_initialization_vector_crc32c: bool = proto.Field( - proto.BOOL, - number=6, - ) - - -class AsymmetricSignResponse(proto.Message): - r"""Response message for - [KeyManagementService.AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign]. - - Attributes: - signature (bytes): - The created signature. - signature_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature]. - An integrity check of - [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature] - can be performed by computing the CRC32C checksum of - [AsymmetricSignResponse.signature][google.cloud.kms.v1.AsymmetricSignResponse.signature] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - verified_digest_crc32c (bool): - Integrity verification field. A flag indicating whether - [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [digest][google.cloud.kms.v1.AsymmetricSignRequest.digest]. - A false value of this field indicates either that - [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [AsymmetricSignRequest.digest_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.digest_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - name (str): - The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for signing. Check this field to verify that the - intended resource was used for signing. - verified_data_crc32c (bool): - Integrity verification field. A flag indicating whether - [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [data][google.cloud.kms.v1.AsymmetricSignRequest.data]. A - false value of this field indicates either that - [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [AsymmetricSignRequest.data_crc32c][google.cloud.kms.v1.AsymmetricSignRequest.data_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for signing. - """ - - signature: bytes = proto.Field( - proto.BYTES, - number=1, - ) - signature_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int64Value, - ) - verified_digest_crc32c: bool = proto.Field( - proto.BOOL, - number=3, - ) - name: str = proto.Field( - proto.STRING, - number=4, - ) - verified_data_crc32c: bool = proto.Field( - proto.BOOL, - number=5, - ) - protection_level: resources.ProtectionLevel = proto.Field( - proto.ENUM, - number=6, - enum=resources.ProtectionLevel, - ) - - -class AsymmetricDecryptResponse(proto.Message): - r"""Response message for - [KeyManagementService.AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt]. - - Attributes: - plaintext (bytes): - The decrypted data originally encrypted with - the matching public key. - plaintext_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext]. - An integrity check of - [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext] - can be performed by computing the CRC32C checksum of - [AsymmetricDecryptResponse.plaintext][google.cloud.kms.v1.AsymmetricDecryptResponse.plaintext] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - verified_ciphertext_crc32c (bool): - Integrity verification field. A flag indicating whether - [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [ciphertext][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext]. - A false value of this field indicates either that - [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [AsymmetricDecryptRequest.ciphertext_crc32c][google.cloud.kms.v1.AsymmetricDecryptRequest.ciphertext_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used in decryption. - """ - - plaintext: bytes = proto.Field( - proto.BYTES, - number=1, - ) - plaintext_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=2, - message=wrappers_pb2.Int64Value, - ) - verified_ciphertext_crc32c: bool = proto.Field( - proto.BOOL, - number=3, - ) - protection_level: resources.ProtectionLevel = proto.Field( - proto.ENUM, - number=4, - enum=resources.ProtectionLevel, - ) - - -class MacSignResponse(proto.Message): - r"""Response message for - [KeyManagementService.MacSign][google.cloud.kms.v1.KeyManagementService.MacSign]. - - Attributes: - name (str): - The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for signing. Check this field to verify that the - intended resource was used for signing. - mac (bytes): - The created signature. - mac_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac]. - An integrity check of - [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac] - can be performed by computing the CRC32C checksum of - [MacSignResponse.mac][google.cloud.kms.v1.MacSignResponse.mac] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - verified_data_crc32c (bool): - Integrity verification field. A flag indicating whether - [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [data][google.cloud.kms.v1.MacSignRequest.data]. A false - value of this field indicates either that - [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [MacSignRequest.data_crc32c][google.cloud.kms.v1.MacSignRequest.data_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for signing. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - mac: bytes = proto.Field( - proto.BYTES, - number=2, - ) - mac_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int64Value, - ) - verified_data_crc32c: bool = proto.Field( - proto.BOOL, - number=4, - ) - protection_level: resources.ProtectionLevel = proto.Field( - proto.ENUM, - number=5, - enum=resources.ProtectionLevel, - ) - - -class MacVerifyResponse(proto.Message): - r"""Response message for - [KeyManagementService.MacVerify][google.cloud.kms.v1.KeyManagementService.MacVerify]. - - Attributes: - name (str): - The resource name of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for verification. Check this field to verify that the - intended resource was used for verification. - success (bool): - This field indicates whether or not the verification - operation for - [MacVerifyRequest.mac][google.cloud.kms.v1.MacVerifyRequest.mac] - over - [MacVerifyRequest.data][google.cloud.kms.v1.MacVerifyRequest.data] - was successful. - verified_data_crc32c (bool): - Integrity verification field. A flag indicating whether - [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [data][google.cloud.kms.v1.MacVerifyRequest.data]. A false - value of this field indicates either that - [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [MacVerifyRequest.data_crc32c][google.cloud.kms.v1.MacVerifyRequest.data_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - verified_mac_crc32c (bool): - Integrity verification field. A flag indicating whether - [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] - was received by - [KeyManagementService][google.cloud.kms.v1.KeyManagementService] - and used for the integrity verification of the - [data][google.cloud.kms.v1.MacVerifyRequest.mac]. A false - value of this field indicates either that - [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] - was left unset or that it was not delivered to - [KeyManagementService][google.cloud.kms.v1.KeyManagementService]. - If you've set - [MacVerifyRequest.mac_crc32c][google.cloud.kms.v1.MacVerifyRequest.mac_crc32c] - but this field is still false, discard the response and - perform a limited number of retries. - verified_success_integrity (bool): - Integrity verification field. This value is used for the - integrity verification of [MacVerifyResponse.success]. If - the value of this field contradicts the value of - [MacVerifyResponse.success], discard the response and - perform a limited number of retries. - protection_level (google.cloud.kms_v1.types.ProtectionLevel): - The [ProtectionLevel][google.cloud.kms.v1.ProtectionLevel] - of the - [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] - used for verification. - """ - - name: str = proto.Field( - proto.STRING, - number=1, - ) - success: bool = proto.Field( - proto.BOOL, - number=2, - ) - verified_data_crc32c: bool = proto.Field( - proto.BOOL, - number=3, - ) - verified_mac_crc32c: bool = proto.Field( - proto.BOOL, - number=4, - ) - verified_success_integrity: bool = proto.Field( - proto.BOOL, - number=5, - ) - protection_level: resources.ProtectionLevel = proto.Field( - proto.ENUM, - number=6, - enum=resources.ProtectionLevel, - ) - - -class GenerateRandomBytesResponse(proto.Message): - r"""Response message for - [KeyManagementService.GenerateRandomBytes][google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes]. - - Attributes: - data (bytes): - The generated data. - data_crc32c (google.protobuf.wrappers_pb2.Int64Value): - Integrity verification field. A CRC32C checksum of the - returned - [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data]. - An integrity check of - [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data] - can be performed by computing the CRC32C checksum of - [GenerateRandomBytesResponse.data][google.cloud.kms.v1.GenerateRandomBytesResponse.data] - and comparing your results to this field. Discard the - response in case of non-matching checksum values, and - perform a limited number of retries. A persistent mismatch - may indicate an issue in your computation of the CRC32C - checksum. Note: This field is defined as int64 for reasons - of compatibility across different languages. However, it is - a non-negative integer, which will never exceed 2^32-1, and - can be safely downconverted to uint32 in languages that - support this type. - """ - - data: bytes = proto.Field( - proto.BYTES, - number=1, - ) - data_crc32c: wrappers_pb2.Int64Value = proto.Field( - proto.MESSAGE, - number=3, - message=wrappers_pb2.Int64Value, - ) - - -class Digest(proto.Message): - r"""A [Digest][google.cloud.kms.v1.Digest] holds a cryptographic message - digest. - - 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: - sha256 (bytes): - A message digest produced with the SHA-256 - algorithm. - - This field is a member of `oneof`_ ``digest``. - sha384 (bytes): - A message digest produced with the SHA-384 - algorithm. - - This field is a member of `oneof`_ ``digest``. - sha512 (bytes): - A message digest produced with the SHA-512 - algorithm. - - This field is a member of `oneof`_ ``digest``. - """ - - sha256: bytes = proto.Field( - proto.BYTES, - number=1, - oneof='digest', - ) - sha384: bytes = proto.Field( - proto.BYTES, - number=2, - oneof='digest', - ) - sha512: bytes = proto.Field( - proto.BYTES, - number=3, - oneof='digest', - ) - - -class LocationMetadata(proto.Message): - r"""Cloud KMS metadata for the given - [google.cloud.location.Location][google.cloud.location.Location]. - - Attributes: - hsm_available (bool): - Indicates whether - [CryptoKeys][google.cloud.kms.v1.CryptoKey] with - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] - [HSM][google.cloud.kms.v1.ProtectionLevel.HSM] can be - created in this location. - ekm_available (bool): - Indicates whether - [CryptoKeys][google.cloud.kms.v1.CryptoKey] with - [protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] - [EXTERNAL][google.cloud.kms.v1.ProtectionLevel.EXTERNAL] can - be created in this location. - """ - - hsm_available: bool = proto.Field( - proto.BOOL, - number=1, - ) - ekm_available: bool = proto.Field( - proto.BOOL, - number=2, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owl-bot-staging/google-cloud-kms/v1/mypy.ini b/owl-bot-staging/google-cloud-kms/v1/mypy.ini deleted file mode 100644 index 574c5aed394b..000000000000 --- a/owl-bot-staging/google-cloud-kms/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-kms/v1/noxfile.py b/owl-bot-staging/google-cloud-kms/v1/noxfile.py deleted file mode 100644 index c69e2b65d2fe..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/noxfile.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -import pathlib -import re -import shutil -import subprocess -import sys - - -import nox # type: ignore - -ALL_PYTHON = [ - "3.7", - "3.8", - "3.9", - "3.10", - "3.11", - "3.12", - "3.13", -] - -CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() - -LOWER_BOUND_CONSTRAINTS_FILE = CURRENT_DIRECTORY / "constraints.txt" -PACKAGE_NAME = 'google-cloud-kms' - -BLACK_VERSION = "black==22.3.0" -BLACK_PATHS = ["docs", "google", "tests", "samples", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.13" - -nox.sessions = [ - "unit", - "cover", - "mypy", - "check_lower_bounds" - # exclude update_lower_bounds from default - "docs", - "blacken", - "lint", - "prerelease_deps", -] - -@nox.session(python=ALL_PYTHON) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def unit(session, protobuf_implementation): - """Run the unit test suite.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - session.install('-e', '.', "-c", f"testing/constraints-{session.python}.txt") - - # Remove the 'cpp' implementation once support for Protobuf 3.x is dropped. - # The 'cpp' implementation requires Protobuf<4. - if protobuf_implementation == "cpp": - session.install("protobuf<4") - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/kms_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - -@nox.session(python=ALL_PYTHON[-1]) -@nox.parametrize( - "protobuf_implementation", - [ "python", "upb", "cpp" ], -) -def prerelease_deps(session, protobuf_implementation): - """Run the unit test suite against pre-release versions of dependencies.""" - - if protobuf_implementation == "cpp" and session.python in ("3.11", "3.12", "3.13"): - session.skip("cpp implementation is not supported in python 3.11+") - - # Install test environment dependencies - session.install('coverage', 'pytest', 'pytest-cov', 'pytest-asyncio', 'asyncmock; python_version < "3.8"') - - # Install the package without dependencies - session.install('-e', '.', '--no-deps') - - # We test the minimum dependency versions using the minimum Python - # version so the lowest python runtime that we test has a corresponding constraints - # file, located at `testing/constraints--.txt`, which contains all of the - # dependencies and extras. - with open( - CURRENT_DIRECTORY - / "testing" - / f"constraints-{ALL_PYTHON[0]}.txt", - encoding="utf-8", - ) as constraints_file: - constraints_text = constraints_file.read() - - # Ignore leading whitespace and comment lines. - constraints_deps = [ - match.group(1) - for match in re.finditer( - r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE - ) - ] - - session.install(*constraints_deps) - - prerel_deps = [ - "googleapis-common-protos", - "google-api-core", - "google-auth", - # Exclude grpcio!=1.67.0rc1 which does not support python 3.13 - "grpcio!=1.67.0rc1", - "grpcio-status", - "protobuf", - "proto-plus", - ] - - for dep in prerel_deps: - session.install("--pre", "--no-deps", "--upgrade", dep) - - # Remaining dependencies - other_deps = [ - "requests", - ] - session.install(*other_deps) - - # Print out prerelease package versions - - session.run("python", "-c", "import google.api_core; print(google.api_core.__version__)") - session.run("python", "-c", "import google.auth; print(google.auth.__version__)") - session.run("python", "-c", "import grpc; print(grpc.__version__)") - session.run( - "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" - ) - session.run( - "python", "-c", "import proto; print(proto.__version__)" - ) - - session.run( - 'py.test', - '--quiet', - '--cov=google/cloud/kms_v1/', - '--cov=tests/', - '--cov-config=.coveragerc', - '--cov-report=term', - '--cov-report=html', - os.path.join('tests', 'unit', ''.join(session.posargs)), - env={ - "PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION": protobuf_implementation, - }, - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def cover(session): - """Run the final coverage report. - This outputs the coverage report aggregating coverage from the unit - test runs (not system test runs), and then erases coverage data. - """ - session.install("coverage", "pytest-cov") - session.run("coverage", "report", "--show-missing", "--fail-under=100") - - session.run("coverage", "erase") - - -@nox.session(python=ALL_PYTHON) -def mypy(session): - """Run the type checker.""" - session.install( - 'mypy', - 'types-requests', - 'types-protobuf' - ) - session.install('.') - session.run( - 'mypy', - '-p', - 'google', - ) - - -@nox.session -def update_lower_bounds(session): - """Update lower bounds in constraints.txt to match setup.py""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'update', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - - -@nox.session -def check_lower_bounds(session): - """Check lower bounds in setup.py are reflected in constraints file""" - session.install('google-cloud-testutils') - session.install('.') - - session.run( - 'lower-bound-checker', - 'check', - '--package-name', - PACKAGE_NAME, - '--constraints-file', - str(LOWER_BOUND_CONSTRAINTS_FILE), - ) - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def docs(session): - """Build the docs for this library.""" - - session.install("-e", ".") - session.install("sphinx==7.0.1", "alabaster", "recommonmark") - - shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) - session.run( - "sphinx-build", - "-W", # warnings as errors - "-T", # show full traceback on exception - "-N", # no colors - "-b", - "html", - "-d", - os.path.join("docs", "_build", "doctrees", ""), - os.path.join("docs", ""), - os.path.join("docs", "_build", "html", ""), - ) - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def lint(session): - """Run linters. - - Returns a failure if the linters find linting errors or sufficiently - serious code quality issues. - """ - session.install("flake8", BLACK_VERSION) - session.run( - "black", - "--check", - *BLACK_PATHS, - ) - session.run("flake8", "google", "tests", "samples") - - -@nox.session(python=DEFAULT_PYTHON_VERSION) -def blacken(session): - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - session.run( - "black", - *BLACK_PATHS, - ) diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py deleted file mode 100644 index ee0d04fe9e37..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAutokeyConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_get_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetAutokeyConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_autokey_config(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py deleted file mode 100644 index f69beed0cc49..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetAutokeyConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_get_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminClient() - - # Initialize request argument(s) - request = kms_v1.GetAutokeyConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_autokey_config(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py deleted file mode 100644 index e1a84b2d8f16..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ShowEffectiveAutokeyConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_show_effective_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ShowEffectiveAutokeyConfigRequest( - parent="parent_value", - ) - - # Make the request - response = await client.show_effective_autokey_config(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py deleted file mode 100644 index 947a97892bd3..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ShowEffectiveAutokeyConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_show_effective_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminClient() - - # Initialize request argument(s) - request = kms_v1.ShowEffectiveAutokeyConfigRequest( - parent="parent_value", - ) - - # Make the request - response = client.show_effective_autokey_config(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py deleted file mode 100644 index 020948ebd222..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAutokeyConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_update_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateAutokeyConfigRequest( - ) - - # Make the request - response = await client.update_autokey_config(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py deleted file mode 100644 index b4b16c13c813..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateAutokeyConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_update_autokey_config(): - # Create a client - client = kms_v1.AutokeyAdminClient() - - # Initialize request argument(s) - request = kms_v1.UpdateAutokeyConfigRequest( - ) - - # Make the request - response = client.update_autokey_config(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_async.py deleted file mode 100644 index 8ce14b9513d9..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_async.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateKeyHandle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_Autokey_CreateKeyHandle_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_create_key_handle(): - # Create a client - client = kms_v1.AutokeyAsyncClient() - - # Initialize request argument(s) - key_handle = kms_v1.KeyHandle() - key_handle.resource_type_selector = "resource_type_selector_value" - - request = kms_v1.CreateKeyHandleRequest( - parent="parent_value", - key_handle=key_handle, - ) - - # Make the request - operation = client.create_key_handle(request=request) - - print("Waiting for operation to complete...") - - response = (await operation).result() - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_Autokey_CreateKeyHandle_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_sync.py deleted file mode 100644 index 694507475e42..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_create_key_handle_sync.py +++ /dev/null @@ -1,60 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateKeyHandle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_Autokey_CreateKeyHandle_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_create_key_handle(): - # Create a client - client = kms_v1.AutokeyClient() - - # Initialize request argument(s) - key_handle = kms_v1.KeyHandle() - key_handle.resource_type_selector = "resource_type_selector_value" - - request = kms_v1.CreateKeyHandleRequest( - parent="parent_value", - key_handle=key_handle, - ) - - # Make the request - operation = client.create_key_handle(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_Autokey_CreateKeyHandle_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_async.py deleted file mode 100644 index 3442ce5864ad..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetKeyHandle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_Autokey_GetKeyHandle_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_get_key_handle(): - # Create a client - client = kms_v1.AutokeyAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetKeyHandleRequest( - name="name_value", - ) - - # Make the request - response = await client.get_key_handle(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_Autokey_GetKeyHandle_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_sync.py deleted file mode 100644 index 08ce1a40467a..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_get_key_handle_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetKeyHandle -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_Autokey_GetKeyHandle_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_get_key_handle(): - # Create a client - client = kms_v1.AutokeyClient() - - # Initialize request argument(s) - request = kms_v1.GetKeyHandleRequest( - name="name_value", - ) - - # Make the request - response = client.get_key_handle(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_Autokey_GetKeyHandle_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_async.py deleted file mode 100644 index bc76498134df..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListKeyHandles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_Autokey_ListKeyHandles_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_list_key_handles(): - # Create a client - client = kms_v1.AutokeyAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListKeyHandlesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_key_handles(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudkms_v1_generated_Autokey_ListKeyHandles_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_sync.py deleted file mode 100644 index 6a7ef9a327e8..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_autokey_list_key_handles_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListKeyHandles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_Autokey_ListKeyHandles_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_list_key_handles(): - # Create a client - client = kms_v1.AutokeyClient() - - # Initialize request argument(s) - request = kms_v1.ListKeyHandlesRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_key_handles(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudkms_v1_generated_Autokey_ListKeyHandles_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py deleted file mode 100644 index 98bb8aa4bdc5..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEkmConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_CreateEkmConnection_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_create_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.CreateEkmConnectionRequest( - parent="parent_value", - ekm_connection_id="ekm_connection_id_value", - ) - - # Make the request - response = await client.create_ekm_connection(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_CreateEkmConnection_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py deleted file mode 100644 index c17c9b6f4e13..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateEkmConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_CreateEkmConnection_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_create_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.CreateEkmConnectionRequest( - parent="parent_value", - ekm_connection_id="ekm_connection_id_value", - ) - - # Make the request - response = client.create_ekm_connection(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_CreateEkmConnection_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_async.py deleted file mode 100644 index e1004f23cd5c..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEkmConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_GetEkmConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_get_ekm_config(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetEkmConfigRequest( - name="name_value", - ) - - # Make the request - response = await client.get_ekm_config(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_GetEkmConfig_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py deleted file mode 100644 index d0abf9952dc4..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEkmConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_GetEkmConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_get_ekm_config(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetEkmConfigRequest( - name="name_value", - ) - - # Make the request - response = client.get_ekm_config(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_GetEkmConfig_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py deleted file mode 100644 index 0ef3b3b2362a..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEkmConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_GetEkmConnection_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_get_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetEkmConnectionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_ekm_connection(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_GetEkmConnection_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py deleted file mode 100644 index 5f711e9b130b..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetEkmConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_GetEkmConnection_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_get_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetEkmConnectionRequest( - name="name_value", - ) - - # Make the request - response = client.get_ekm_connection(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_GetEkmConnection_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py deleted file mode 100644 index a7f411307441..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEkmConnections -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_ListEkmConnections_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_list_ekm_connections(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListEkmConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_ekm_connections(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudkms_v1_generated_EkmService_ListEkmConnections_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py deleted file mode 100644 index 9455ecdf9518..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListEkmConnections -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_ListEkmConnections_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_list_ekm_connections(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.ListEkmConnectionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_ekm_connections(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudkms_v1_generated_EkmService_ListEkmConnections_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_async.py deleted file mode 100644 index 9403690e5be2..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEkmConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_UpdateEkmConfig_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_update_ekm_config(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateEkmConfigRequest( - ) - - # Make the request - response = await client.update_ekm_config(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_UpdateEkmConfig_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py deleted file mode 100644 index 7357a475cd7e..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEkmConfig -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_UpdateEkmConfig_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_update_ekm_config(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.UpdateEkmConfigRequest( - ) - - # Make the request - response = client.update_ekm_config(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_UpdateEkmConfig_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py deleted file mode 100644 index 8f61b8003f64..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEkmConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_UpdateEkmConnection_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_update_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateEkmConnectionRequest( - ) - - # Make the request - response = await client.update_ekm_connection(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_UpdateEkmConnection_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py deleted file mode 100644 index 7d3637358348..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateEkmConnection -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_UpdateEkmConnection_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_update_ekm_connection(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.UpdateEkmConnectionRequest( - ) - - # Make the request - response = client.update_ekm_connection(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_UpdateEkmConnection_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py deleted file mode 100644 index fb5824c4f4ac..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for VerifyConnectivity -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_VerifyConnectivity_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_verify_connectivity(): - # Create a client - client = kms_v1.EkmServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.VerifyConnectivityRequest( - name="name_value", - ) - - # Make the request - response = await client.verify_connectivity(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_VerifyConnectivity_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py deleted file mode 100644 index 1ce849c0520e..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for VerifyConnectivity -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_EkmService_VerifyConnectivity_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_verify_connectivity(): - # Create a client - client = kms_v1.EkmServiceClient() - - # Initialize request argument(s) - request = kms_v1.VerifyConnectivityRequest( - name="name_value", - ) - - # Make the request - response = client.verify_connectivity(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_EkmService_VerifyConnectivity_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py deleted file mode 100644 index 0276698153e2..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AsymmetricDecrypt -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_asymmetric_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.AsymmetricDecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - ) - - # Make the request - response = await client.asymmetric_decrypt(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py deleted file mode 100644 index f42b4ed1668f..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AsymmetricDecrypt -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_asymmetric_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.AsymmetricDecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - ) - - # Make the request - response = client.asymmetric_decrypt(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py deleted file mode 100644 index 1039bdc4ee07..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AsymmetricSign -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_AsymmetricSign_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_asymmetric_sign(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.AsymmetricSignRequest( - name="name_value", - ) - - # Make the request - response = await client.asymmetric_sign(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_AsymmetricSign_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py deleted file mode 100644 index e2a99a9f4da9..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for AsymmetricSign -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_AsymmetricSign_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_asymmetric_sign(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.AsymmetricSignRequest( - name="name_value", - ) - - # Make the request - response = client.asymmetric_sign(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_AsymmetricSign_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_async.py deleted file mode 100644 index f2bf2b416d4e..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateCryptoKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_create_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.CreateCryptoKeyRequest( - parent="parent_value", - crypto_key_id="crypto_key_id_value", - ) - - # Make the request - response = await client.create_crypto_key(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py deleted file mode 100644 index c1bc6cbe4d55..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateCryptoKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_create_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.CreateCryptoKeyRequest( - parent="parent_value", - crypto_key_id="crypto_key_id_value", - ) - - # Make the request - response = client.create_crypto_key(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py deleted file mode 100644 index 017d5d7f0ffd..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_create_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.CreateCryptoKeyVersionRequest( - parent="parent_value", - ) - - # Make the request - response = await client.create_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py deleted file mode 100644 index ad0ef21ebc81..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_create_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.CreateCryptoKeyVersionRequest( - parent="parent_value", - ) - - # Make the request - response = client.create_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py deleted file mode 100644 index 662876ffc8de..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_async.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateImportJob -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_CreateImportJob_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_create_import_job(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - import_job = kms_v1.ImportJob() - import_job.import_method = "RSA_OAEP_4096_SHA256" - import_job.protection_level = "EXTERNAL_VPC" - - request = kms_v1.CreateImportJobRequest( - parent="parent_value", - import_job_id="import_job_id_value", - import_job=import_job, - ) - - # Make the request - response = await client.create_import_job(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_CreateImportJob_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py deleted file mode 100644 index 86f5887b9b19..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_import_job_sync.py +++ /dev/null @@ -1,58 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateImportJob -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_CreateImportJob_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_create_import_job(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - import_job = kms_v1.ImportJob() - import_job.import_method = "RSA_OAEP_4096_SHA256" - import_job.protection_level = "EXTERNAL_VPC" - - request = kms_v1.CreateImportJobRequest( - parent="parent_value", - import_job_id="import_job_id_value", - import_job=import_job, - ) - - # Make the request - response = client.create_import_job(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_CreateImportJob_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_async.py deleted file mode 100644 index 40bc57c5850a..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateKeyRing -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_CreateKeyRing_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_create_key_ring(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.CreateKeyRingRequest( - parent="parent_value", - key_ring_id="key_ring_id_value", - ) - - # Make the request - response = await client.create_key_ring(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_CreateKeyRing_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_sync.py deleted file mode 100644 index 736928f89f04..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_create_key_ring_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for CreateKeyRing -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_CreateKeyRing_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_create_key_ring(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.CreateKeyRingRequest( - parent="parent_value", - key_ring_id="key_ring_id_value", - ) - - # Make the request - response = client.create_key_ring(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_CreateKeyRing_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_async.py deleted file mode 100644 index f691ae9aa828..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Decrypt -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_Decrypt_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.DecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - ) - - # Make the request - response = await client.decrypt(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_Decrypt_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_sync.py deleted file mode 100644 index 49fc5586472d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_decrypt_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Decrypt -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_Decrypt_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.DecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - ) - - # Make the request - response = client.decrypt(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_Decrypt_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py deleted file mode 100644 index 3f7b361ee2c9..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DestroyCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_destroy_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.DestroyCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.destroy_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py deleted file mode 100644 index 6b21af5853a9..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for DestroyCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_destroy_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.DestroyCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = client.destroy_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_async.py deleted file mode 100644 index 1610fe4564ac..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Encrypt -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_Encrypt_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_encrypt(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.EncryptRequest( - name="name_value", - plaintext=b'plaintext_blob', - ) - - # Make the request - response = await client.encrypt(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_Encrypt_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_sync.py deleted file mode 100644 index b3cfa5969cd0..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_encrypt_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for Encrypt -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_Encrypt_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_encrypt(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.EncryptRequest( - name="name_value", - plaintext=b'plaintext_blob', - ) - - # Make the request - response = client.encrypt(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_Encrypt_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py deleted file mode 100644 index 36302635dc0d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateRandomBytes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_generate_random_bytes(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GenerateRandomBytesRequest( - ) - - # Make the request - response = await client.generate_random_bytes(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py deleted file mode 100644 index 58d57585b1d2..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GenerateRandomBytes -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_generate_random_bytes(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GenerateRandomBytesRequest( - ) - - # Make the request - response = client.generate_random_bytes(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_async.py deleted file mode 100644 index 28e6ee8c09cb..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCryptoKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GetCryptoKey_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_get_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetCryptoKeyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_crypto_key(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GetCryptoKey_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py deleted file mode 100644 index 98c022e4110a..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCryptoKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GetCryptoKey_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_get_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetCryptoKeyRequest( - name="name_value", - ) - - # Make the request - response = client.get_crypto_key(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GetCryptoKey_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py deleted file mode 100644 index 0b5b907c76af..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_get_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.get_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py deleted file mode 100644 index 3f06a8ddaef8..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_get_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = client.get_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_async.py deleted file mode 100644 index 8fb0f45dab95..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetImportJob -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GetImportJob_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_get_import_job(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetImportJobRequest( - name="name_value", - ) - - # Make the request - response = await client.get_import_job(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GetImportJob_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_sync.py deleted file mode 100644 index c3cbf2233ced..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_import_job_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetImportJob -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GetImportJob_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_get_import_job(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetImportJobRequest( - name="name_value", - ) - - # Make the request - response = client.get_import_job(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GetImportJob_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_async.py deleted file mode 100644 index 88905b3c9428..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetKeyRing -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GetKeyRing_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_get_key_ring(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetKeyRingRequest( - name="name_value", - ) - - # Make the request - response = await client.get_key_ring(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GetKeyRing_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_sync.py deleted file mode 100644 index eb7c44e6b68e..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_key_ring_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetKeyRing -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GetKeyRing_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_get_key_ring(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetKeyRingRequest( - name="name_value", - ) - - # Make the request - response = client.get_key_ring(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GetKeyRing_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_async.py deleted file mode 100644 index 3086b8d6b6f7..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetPublicKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GetPublicKey_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_get_public_key(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.GetPublicKeyRequest( - name="name_value", - ) - - # Make the request - response = await client.get_public_key(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GetPublicKey_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_sync.py deleted file mode 100644 index 312dcf004425..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_get_public_key_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for GetPublicKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_GetPublicKey_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_get_public_key(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.GetPublicKeyRequest( - name="name_value", - ) - - # Make the request - response = client.get_public_key(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_GetPublicKey_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py deleted file mode 100644 index b7ab7f35c87d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_import_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ImportCryptoKeyVersionRequest( - rsa_aes_wrapped_key=b'rsa_aes_wrapped_key_blob', - parent="parent_value", - algorithm="EXTERNAL_SYMMETRIC_ENCRYPTION", - import_job="import_job_value", - ) - - # Make the request - response = await client.import_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py deleted file mode 100644 index cf0102d4121d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py +++ /dev/null @@ -1,55 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ImportCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_import_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.ImportCryptoKeyVersionRequest( - rsa_aes_wrapped_key=b'rsa_aes_wrapped_key_blob', - parent="parent_value", - algorithm="EXTERNAL_SYMMETRIC_ENCRYPTION", - import_job="import_job_value", - ) - - # Make the request - response = client.import_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py deleted file mode 100644 index 55bf1e3276fc..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCryptoKeyVersions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_list_crypto_key_versions(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListCryptoKeyVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crypto_key_versions(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py deleted file mode 100644 index 37d7ded635b2..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCryptoKeyVersions -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_list_crypto_key_versions(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.ListCryptoKeyVersionsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crypto_key_versions(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py deleted file mode 100644 index 3c090ebdc3e4..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCryptoKeys -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_list_crypto_keys(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListCryptoKeysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crypto_keys(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py deleted file mode 100644 index 603c44280859..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListCryptoKeys -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_list_crypto_keys(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.ListCryptoKeysRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_crypto_keys(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_async.py deleted file mode 100644 index 53e15d99d257..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListImportJobs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_ListImportJobs_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_list_import_jobs(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListImportJobsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_import_jobs(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_ListImportJobs_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py deleted file mode 100644 index 981b33b05542..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListImportJobs -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_ListImportJobs_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_list_import_jobs(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.ListImportJobsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_import_jobs(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_ListImportJobs_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_async.py deleted file mode 100644 index d9bab55db774..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListKeyRings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_ListKeyRings_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_list_key_rings(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.ListKeyRingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_key_rings(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_ListKeyRings_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_sync.py deleted file mode 100644 index 1440579645ce..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_list_key_rings_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for ListKeyRings -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_ListKeyRings_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_list_key_rings(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.ListKeyRingsRequest( - parent="parent_value", - ) - - # Make the request - page_result = client.list_key_rings(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_ListKeyRings_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_async.py deleted file mode 100644 index deb3ae7bef8a..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for MacSign -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_MacSign_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_mac_sign(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.MacSignRequest( - name="name_value", - data=b'data_blob', - ) - - # Make the request - response = await client.mac_sign(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_MacSign_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_sync.py deleted file mode 100644 index c86d67b11ca8..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_sign_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for MacSign -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_MacSign_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_mac_sign(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.MacSignRequest( - name="name_value", - data=b'data_blob', - ) - - # Make the request - response = client.mac_sign(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_MacSign_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_async.py deleted file mode 100644 index 88cd1afc72d1..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for MacVerify -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_MacVerify_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_mac_verify(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.MacVerifyRequest( - name="name_value", - data=b'data_blob', - mac=b'mac_blob', - ) - - # Make the request - response = await client.mac_verify(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_MacVerify_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_sync.py deleted file mode 100644 index 4e884e7ead1e..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_mac_verify_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for MacVerify -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_MacVerify_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_mac_verify(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.MacVerifyRequest( - name="name_value", - data=b'data_blob', - mac=b'mac_blob', - ) - - # Make the request - response = client.mac_verify(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_MacVerify_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_async.py deleted file mode 100644 index 85327867bde0..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RawDecrypt -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_RawDecrypt_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_raw_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.RawDecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - initialization_vector=b'initialization_vector_blob', - ) - - # Make the request - response = await client.raw_decrypt(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_RawDecrypt_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py deleted file mode 100644 index 516eb485779b..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RawDecrypt -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_RawDecrypt_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_raw_decrypt(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.RawDecryptRequest( - name="name_value", - ciphertext=b'ciphertext_blob', - initialization_vector=b'initialization_vector_blob', - ) - - # Make the request - response = client.raw_decrypt(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_RawDecrypt_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_async.py deleted file mode 100644 index 0dd788632a8e..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RawEncrypt -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_RawEncrypt_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_raw_encrypt(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.RawEncryptRequest( - name="name_value", - plaintext=b'plaintext_blob', - ) - - # Make the request - response = await client.raw_encrypt(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_RawEncrypt_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py deleted file mode 100644 index b6fa3e7ea53f..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RawEncrypt -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_RawEncrypt_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_raw_encrypt(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.RawEncryptRequest( - name="name_value", - plaintext=b'plaintext_blob', - ) - - # Make the request - response = client.raw_encrypt(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_RawEncrypt_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py deleted file mode 100644 index d66756fc32f8..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RestoreCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_restore_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.RestoreCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = await client.restore_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py deleted file mode 100644 index ae7c6d2aa877..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for RestoreCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_restore_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.RestoreCryptoKeyVersionRequest( - name="name_value", - ) - - # Make the request - response = client.restore_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_async.py deleted file mode 100644 index d627815cc24d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCryptoKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_update_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyRequest( - ) - - # Make the request - response = await client.update_crypto_key(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py deleted file mode 100644 index ccd953a70e17..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCryptoKeyPrimaryVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_update_crypto_key_primary_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyPrimaryVersionRequest( - name="name_value", - crypto_key_version_id="crypto_key_version_id_value", - ) - - # Make the request - response = await client.update_crypto_key_primary_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py deleted file mode 100644 index e7f3cbe542de..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCryptoKeyPrimaryVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_update_crypto_key_primary_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyPrimaryVersionRequest( - name="name_value", - crypto_key_version_id="crypto_key_version_id_value", - ) - - # Make the request - response = client.update_crypto_key_primary_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py deleted file mode 100644 index 6fa8b692bd6e..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCryptoKey -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_update_crypto_key(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyRequest( - ) - - # Make the request - response = client.update_crypto_key(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py deleted file mode 100644 index d11fbe440196..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -async def sample_update_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceAsyncClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyVersionRequest( - ) - - # Make the request - response = await client.update_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_async] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py deleted file mode 100644 index bd1a3cbc23eb..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateCryptoKeyVersion -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-kms - - -# [START cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.cloud import kms_v1 - - -def sample_update_crypto_key_version(): - # Create a client - client = kms_v1.KeyManagementServiceClient() - - # Initialize request argument(s) - request = kms_v1.UpdateCryptoKeyVersionRequest( - ) - - # Make the request - response = client.update_crypto_key_version(request=request) - - # Handle the response - print(response) - -# [END cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_sync] diff --git a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json b/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json deleted file mode 100644 index a5e165bff4c4..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json +++ /dev/null @@ -1,6800 +0,0 @@ -{ - "clientLibrary": { - "apis": [ - { - "id": "google.cloud.kms.v1", - "version": "v1" - } - ], - "language": "PYTHON", - "name": "google-cloud-kms", - "version": "0.1.0" - }, - "snippets": [ - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient", - "shortName": "AutokeyAdminAsyncClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient.get_autokey_config", - "method": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig", - "service": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin", - "shortName": "AutokeyAdmin" - }, - "shortName": "GetAutokeyConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetAutokeyConfigRequest" - }, - { - "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.kms_v1.types.AutokeyConfig", - "shortName": "get_autokey_config" - }, - "description": "Sample for GetAutokeyConfig", - "file": "cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_get_autokey_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.AutokeyAdminClient", - "shortName": "AutokeyAdminClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyAdminClient.get_autokey_config", - "method": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin.GetAutokeyConfig", - "service": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin", - "shortName": "AutokeyAdmin" - }, - "shortName": "GetAutokeyConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetAutokeyConfigRequest" - }, - { - "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.kms_v1.types.AutokeyConfig", - "shortName": "get_autokey_config" - }, - "description": "Sample for GetAutokeyConfig", - "file": "cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_AutokeyAdmin_GetAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_get_autokey_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient", - "shortName": "AutokeyAdminAsyncClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient.show_effective_autokey_config", - "method": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig", - "service": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin", - "shortName": "AutokeyAdmin" - }, - "shortName": "ShowEffectiveAutokeyConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ShowEffectiveAutokeyConfigRequest" - }, - { - "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.kms_v1.types.ShowEffectiveAutokeyConfigResponse", - "shortName": "show_effective_autokey_config" - }, - "description": "Sample for ShowEffectiveAutokeyConfig", - "file": "cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.AutokeyAdminClient", - "shortName": "AutokeyAdminClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyAdminClient.show_effective_autokey_config", - "method": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin.ShowEffectiveAutokeyConfig", - "service": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin", - "shortName": "AutokeyAdmin" - }, - "shortName": "ShowEffectiveAutokeyConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ShowEffectiveAutokeyConfigRequest" - }, - { - "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.kms_v1.types.ShowEffectiveAutokeyConfigResponse", - "shortName": "show_effective_autokey_config" - }, - "description": "Sample for ShowEffectiveAutokeyConfig", - "file": "cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_AutokeyAdmin_ShowEffectiveAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_show_effective_autokey_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient", - "shortName": "AutokeyAdminAsyncClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyAdminAsyncClient.update_autokey_config", - "method": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig", - "service": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin", - "shortName": "AutokeyAdmin" - }, - "shortName": "UpdateAutokeyConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateAutokeyConfigRequest" - }, - { - "name": "autokey_config", - "type": "google.cloud.kms_v1.types.AutokeyConfig" - }, - { - "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.cloud.kms_v1.types.AutokeyConfig", - "shortName": "update_autokey_config" - }, - "description": "Sample for UpdateAutokeyConfig", - "file": "cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_update_autokey_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.AutokeyAdminClient", - "shortName": "AutokeyAdminClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyAdminClient.update_autokey_config", - "method": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin.UpdateAutokeyConfig", - "service": { - "fullName": "google.cloud.kms.v1.AutokeyAdmin", - "shortName": "AutokeyAdmin" - }, - "shortName": "UpdateAutokeyConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateAutokeyConfigRequest" - }, - { - "name": "autokey_config", - "type": "google.cloud.kms_v1.types.AutokeyConfig" - }, - { - "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.cloud.kms_v1.types.AutokeyConfig", - "shortName": "update_autokey_config" - }, - "description": "Sample for UpdateAutokeyConfig", - "file": "cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_AutokeyAdmin_UpdateAutokeyConfig_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": "cloudkms_v1_generated_autokey_admin_update_autokey_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.AutokeyAsyncClient", - "shortName": "AutokeyAsyncClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyAsyncClient.create_key_handle", - "method": { - "fullName": "google.cloud.kms.v1.Autokey.CreateKeyHandle", - "service": { - "fullName": "google.cloud.kms.v1.Autokey", - "shortName": "Autokey" - }, - "shortName": "CreateKeyHandle" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateKeyHandleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "key_handle", - "type": "google.cloud.kms_v1.types.KeyHandle" - }, - { - "name": "key_handle_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_key_handle" - }, - "description": "Sample for CreateKeyHandle", - "file": "cloudkms_v1_generated_autokey_create_key_handle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_Autokey_CreateKeyHandle_async", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_autokey_create_key_handle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.AutokeyClient", - "shortName": "AutokeyClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyClient.create_key_handle", - "method": { - "fullName": "google.cloud.kms.v1.Autokey.CreateKeyHandle", - "service": { - "fullName": "google.cloud.kms.v1.Autokey", - "shortName": "Autokey" - }, - "shortName": "CreateKeyHandle" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateKeyHandleRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "key_handle", - "type": "google.cloud.kms_v1.types.KeyHandle" - }, - { - "name": "key_handle_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_key_handle" - }, - "description": "Sample for CreateKeyHandle", - "file": "cloudkms_v1_generated_autokey_create_key_handle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_Autokey_CreateKeyHandle_sync", - "segments": [ - { - "end": 59, - "start": 27, - "type": "FULL" - }, - { - "end": 59, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 49, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 56, - "start": 50, - "type": "REQUEST_EXECUTION" - }, - { - "end": 60, - "start": 57, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_autokey_create_key_handle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.AutokeyAsyncClient", - "shortName": "AutokeyAsyncClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyAsyncClient.get_key_handle", - "method": { - "fullName": "google.cloud.kms.v1.Autokey.GetKeyHandle", - "service": { - "fullName": "google.cloud.kms.v1.Autokey", - "shortName": "Autokey" - }, - "shortName": "GetKeyHandle" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetKeyHandleRequest" - }, - { - "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.kms_v1.types.KeyHandle", - "shortName": "get_key_handle" - }, - "description": "Sample for GetKeyHandle", - "file": "cloudkms_v1_generated_autokey_get_key_handle_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_Autokey_GetKeyHandle_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": "cloudkms_v1_generated_autokey_get_key_handle_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.AutokeyClient", - "shortName": "AutokeyClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyClient.get_key_handle", - "method": { - "fullName": "google.cloud.kms.v1.Autokey.GetKeyHandle", - "service": { - "fullName": "google.cloud.kms.v1.Autokey", - "shortName": "Autokey" - }, - "shortName": "GetKeyHandle" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetKeyHandleRequest" - }, - { - "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.kms_v1.types.KeyHandle", - "shortName": "get_key_handle" - }, - "description": "Sample for GetKeyHandle", - "file": "cloudkms_v1_generated_autokey_get_key_handle_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_Autokey_GetKeyHandle_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": "cloudkms_v1_generated_autokey_get_key_handle_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.AutokeyAsyncClient", - "shortName": "AutokeyAsyncClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyAsyncClient.list_key_handles", - "method": { - "fullName": "google.cloud.kms.v1.Autokey.ListKeyHandles", - "service": { - "fullName": "google.cloud.kms.v1.Autokey", - "shortName": "Autokey" - }, - "shortName": "ListKeyHandles" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListKeyHandlesRequest" - }, - { - "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.kms_v1.services.autokey.pagers.ListKeyHandlesAsyncPager", - "shortName": "list_key_handles" - }, - "description": "Sample for ListKeyHandles", - "file": "cloudkms_v1_generated_autokey_list_key_handles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_Autokey_ListKeyHandles_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_autokey_list_key_handles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.AutokeyClient", - "shortName": "AutokeyClient" - }, - "fullName": "google.cloud.kms_v1.AutokeyClient.list_key_handles", - "method": { - "fullName": "google.cloud.kms.v1.Autokey.ListKeyHandles", - "service": { - "fullName": "google.cloud.kms.v1.Autokey", - "shortName": "Autokey" - }, - "shortName": "ListKeyHandles" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListKeyHandlesRequest" - }, - { - "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.kms_v1.services.autokey.pagers.ListKeyHandlesPager", - "shortName": "list_key_handles" - }, - "description": "Sample for ListKeyHandles", - "file": "cloudkms_v1_generated_autokey_list_key_handles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_Autokey_ListKeyHandles_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_autokey_list_key_handles_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", - "shortName": "EkmServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.create_ekm_connection", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.CreateEkmConnection", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "CreateEkmConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateEkmConnectionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "ekm_connection_id", - "type": "str" - }, - { - "name": "ekm_connection", - "type": "google.cloud.kms_v1.types.EkmConnection" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.EkmConnection", - "shortName": "create_ekm_connection" - }, - "description": "Sample for CreateEkmConnection", - "file": "cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_CreateEkmConnection_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_ekm_service_create_ekm_connection_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceClient", - "shortName": "EkmServiceClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceClient.create_ekm_connection", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.CreateEkmConnection", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "CreateEkmConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateEkmConnectionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "ekm_connection_id", - "type": "str" - }, - { - "name": "ekm_connection", - "type": "google.cloud.kms_v1.types.EkmConnection" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.EkmConnection", - "shortName": "create_ekm_connection" - }, - "description": "Sample for CreateEkmConnection", - "file": "cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_CreateEkmConnection_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_ekm_service_create_ekm_connection_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", - "shortName": "EkmServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.get_ekm_config", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.GetEkmConfig", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "GetEkmConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetEkmConfigRequest" - }, - { - "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.kms_v1.types.EkmConfig", - "shortName": "get_ekm_config" - }, - "description": "Sample for GetEkmConfig", - "file": "cloudkms_v1_generated_ekm_service_get_ekm_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_GetEkmConfig_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": "cloudkms_v1_generated_ekm_service_get_ekm_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceClient", - "shortName": "EkmServiceClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceClient.get_ekm_config", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.GetEkmConfig", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "GetEkmConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetEkmConfigRequest" - }, - { - "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.kms_v1.types.EkmConfig", - "shortName": "get_ekm_config" - }, - "description": "Sample for GetEkmConfig", - "file": "cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_GetEkmConfig_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": "cloudkms_v1_generated_ekm_service_get_ekm_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", - "shortName": "EkmServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.get_ekm_connection", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.GetEkmConnection", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "GetEkmConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetEkmConnectionRequest" - }, - { - "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.kms_v1.types.EkmConnection", - "shortName": "get_ekm_connection" - }, - "description": "Sample for GetEkmConnection", - "file": "cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_GetEkmConnection_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": "cloudkms_v1_generated_ekm_service_get_ekm_connection_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceClient", - "shortName": "EkmServiceClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceClient.get_ekm_connection", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.GetEkmConnection", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "GetEkmConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetEkmConnectionRequest" - }, - { - "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.kms_v1.types.EkmConnection", - "shortName": "get_ekm_connection" - }, - "description": "Sample for GetEkmConnection", - "file": "cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_GetEkmConnection_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": "cloudkms_v1_generated_ekm_service_get_ekm_connection_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", - "shortName": "EkmServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.list_ekm_connections", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.ListEkmConnections", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "ListEkmConnections" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListEkmConnectionsRequest" - }, - { - "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.kms_v1.services.ekm_service.pagers.ListEkmConnectionsAsyncPager", - "shortName": "list_ekm_connections" - }, - "description": "Sample for ListEkmConnections", - "file": "cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_ListEkmConnections_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_ekm_service_list_ekm_connections_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceClient", - "shortName": "EkmServiceClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceClient.list_ekm_connections", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.ListEkmConnections", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "ListEkmConnections" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListEkmConnectionsRequest" - }, - { - "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.kms_v1.services.ekm_service.pagers.ListEkmConnectionsPager", - "shortName": "list_ekm_connections" - }, - "description": "Sample for ListEkmConnections", - "file": "cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_ListEkmConnections_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_ekm_service_list_ekm_connections_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", - "shortName": "EkmServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.update_ekm_config", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.UpdateEkmConfig", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "UpdateEkmConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateEkmConfigRequest" - }, - { - "name": "ekm_config", - "type": "google.cloud.kms_v1.types.EkmConfig" - }, - { - "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.cloud.kms_v1.types.EkmConfig", - "shortName": "update_ekm_config" - }, - "description": "Sample for UpdateEkmConfig", - "file": "cloudkms_v1_generated_ekm_service_update_ekm_config_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_UpdateEkmConfig_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": "cloudkms_v1_generated_ekm_service_update_ekm_config_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceClient", - "shortName": "EkmServiceClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceClient.update_ekm_config", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.UpdateEkmConfig", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "UpdateEkmConfig" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateEkmConfigRequest" - }, - { - "name": "ekm_config", - "type": "google.cloud.kms_v1.types.EkmConfig" - }, - { - "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.cloud.kms_v1.types.EkmConfig", - "shortName": "update_ekm_config" - }, - "description": "Sample for UpdateEkmConfig", - "file": "cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_UpdateEkmConfig_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": "cloudkms_v1_generated_ekm_service_update_ekm_config_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", - "shortName": "EkmServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.update_ekm_connection", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.UpdateEkmConnection", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "UpdateEkmConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateEkmConnectionRequest" - }, - { - "name": "ekm_connection", - "type": "google.cloud.kms_v1.types.EkmConnection" - }, - { - "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.cloud.kms_v1.types.EkmConnection", - "shortName": "update_ekm_connection" - }, - "description": "Sample for UpdateEkmConnection", - "file": "cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_UpdateEkmConnection_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": "cloudkms_v1_generated_ekm_service_update_ekm_connection_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceClient", - "shortName": "EkmServiceClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceClient.update_ekm_connection", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.UpdateEkmConnection", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "UpdateEkmConnection" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateEkmConnectionRequest" - }, - { - "name": "ekm_connection", - "type": "google.cloud.kms_v1.types.EkmConnection" - }, - { - "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.cloud.kms_v1.types.EkmConnection", - "shortName": "update_ekm_connection" - }, - "description": "Sample for UpdateEkmConnection", - "file": "cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_UpdateEkmConnection_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": "cloudkms_v1_generated_ekm_service_update_ekm_connection_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient", - "shortName": "EkmServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceAsyncClient.verify_connectivity", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.VerifyConnectivity", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "VerifyConnectivity" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.VerifyConnectivityRequest" - }, - { - "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.kms_v1.types.VerifyConnectivityResponse", - "shortName": "verify_connectivity" - }, - "description": "Sample for VerifyConnectivity", - "file": "cloudkms_v1_generated_ekm_service_verify_connectivity_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_VerifyConnectivity_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": "cloudkms_v1_generated_ekm_service_verify_connectivity_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.EkmServiceClient", - "shortName": "EkmServiceClient" - }, - "fullName": "google.cloud.kms_v1.EkmServiceClient.verify_connectivity", - "method": { - "fullName": "google.cloud.kms.v1.EkmService.VerifyConnectivity", - "service": { - "fullName": "google.cloud.kms.v1.EkmService", - "shortName": "EkmService" - }, - "shortName": "VerifyConnectivity" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.VerifyConnectivityRequest" - }, - { - "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.kms_v1.types.VerifyConnectivityResponse", - "shortName": "verify_connectivity" - }, - "description": "Sample for VerifyConnectivity", - "file": "cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_EkmService_VerifyConnectivity_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": "cloudkms_v1_generated_ekm_service_verify_connectivity_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.asymmetric_decrypt", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "AsymmetricDecrypt" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.AsymmetricDecryptRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "ciphertext", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.AsymmetricDecryptResponse", - "shortName": "asymmetric_decrypt" - }, - "description": "Sample for AsymmetricDecrypt", - "file": "cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_asymmetric_decrypt_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.asymmetric_decrypt", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "AsymmetricDecrypt" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.AsymmetricDecryptRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "ciphertext", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.AsymmetricDecryptResponse", - "shortName": "asymmetric_decrypt" - }, - "description": "Sample for AsymmetricDecrypt", - "file": "cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_AsymmetricDecrypt_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_asymmetric_decrypt_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.asymmetric_sign", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.AsymmetricSign", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "AsymmetricSign" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.AsymmetricSignRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "digest", - "type": "google.cloud.kms_v1.types.Digest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.AsymmetricSignResponse", - "shortName": "asymmetric_sign" - }, - "description": "Sample for AsymmetricSign", - "file": "cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_AsymmetricSign_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": "cloudkms_v1_generated_key_management_service_asymmetric_sign_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.asymmetric_sign", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.AsymmetricSign", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "AsymmetricSign" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.AsymmetricSignRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "digest", - "type": "google.cloud.kms_v1.types.Digest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.AsymmetricSignResponse", - "shortName": "asymmetric_sign" - }, - "description": "Sample for AsymmetricSign", - "file": "cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_AsymmetricSign_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": "cloudkms_v1_generated_key_management_service_asymmetric_sign_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.create_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "CreateCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "crypto_key_version", - "type": "google.cloud.kms_v1.types.CryptoKeyVersion" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.CryptoKeyVersion", - "shortName": "create_crypto_key_version" - }, - "description": "Sample for CreateCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_create_crypto_key_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.create_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "CreateCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateCryptoKeyVersionRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "crypto_key_version", - "type": "google.cloud.kms_v1.types.CryptoKeyVersion" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.CryptoKeyVersion", - "shortName": "create_crypto_key_version" - }, - "description": "Sample for CreateCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_create_crypto_key_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.create_crypto_key", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.CreateCryptoKey", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "CreateCryptoKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateCryptoKeyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "crypto_key_id", - "type": "str" - }, - { - "name": "crypto_key", - "type": "google.cloud.kms_v1.types.CryptoKey" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.CryptoKey", - "shortName": "create_crypto_key" - }, - "description": "Sample for CreateCryptoKey", - "file": "cloudkms_v1_generated_key_management_service_create_crypto_key_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_create_crypto_key_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.create_crypto_key", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.CreateCryptoKey", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "CreateCryptoKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateCryptoKeyRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "crypto_key_id", - "type": "str" - }, - { - "name": "crypto_key", - "type": "google.cloud.kms_v1.types.CryptoKey" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.CryptoKey", - "shortName": "create_crypto_key" - }, - "description": "Sample for CreateCryptoKey", - "file": "cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateCryptoKey_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_create_crypto_key_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.create_import_job", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.CreateImportJob", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "CreateImportJob" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateImportJobRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "import_job_id", - "type": "str" - }, - { - "name": "import_job", - "type": "google.cloud.kms_v1.types.ImportJob" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.ImportJob", - "shortName": "create_import_job" - }, - "description": "Sample for CreateImportJob", - "file": "cloudkms_v1_generated_key_management_service_create_import_job_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateImportJob_async", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_create_import_job_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.create_import_job", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.CreateImportJob", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "CreateImportJob" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateImportJobRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "import_job_id", - "type": "str" - }, - { - "name": "import_job", - "type": "google.cloud.kms_v1.types.ImportJob" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.ImportJob", - "shortName": "create_import_job" - }, - "description": "Sample for CreateImportJob", - "file": "cloudkms_v1_generated_key_management_service_create_import_job_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateImportJob_sync", - "segments": [ - { - "end": 57, - "start": 27, - "type": "FULL" - }, - { - "end": 57, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 51, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 54, - "start": 52, - "type": "REQUEST_EXECUTION" - }, - { - "end": 58, - "start": 55, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_create_import_job_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.create_key_ring", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.CreateKeyRing", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "CreateKeyRing" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateKeyRingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "key_ring_id", - "type": "str" - }, - { - "name": "key_ring", - "type": "google.cloud.kms_v1.types.KeyRing" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.KeyRing", - "shortName": "create_key_ring" - }, - "description": "Sample for CreateKeyRing", - "file": "cloudkms_v1_generated_key_management_service_create_key_ring_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateKeyRing_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_create_key_ring_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.create_key_ring", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.CreateKeyRing", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "CreateKeyRing" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.CreateKeyRingRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "key_ring_id", - "type": "str" - }, - { - "name": "key_ring", - "type": "google.cloud.kms_v1.types.KeyRing" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.KeyRing", - "shortName": "create_key_ring" - }, - "description": "Sample for CreateKeyRing", - "file": "cloudkms_v1_generated_key_management_service_create_key_ring_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_CreateKeyRing_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_create_key_ring_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.decrypt", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.Decrypt", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "Decrypt" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.DecryptRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "ciphertext", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.DecryptResponse", - "shortName": "decrypt" - }, - "description": "Sample for Decrypt", - "file": "cloudkms_v1_generated_key_management_service_decrypt_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_Decrypt_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_decrypt_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.decrypt", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.Decrypt", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "Decrypt" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.DecryptRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "ciphertext", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.DecryptResponse", - "shortName": "decrypt" - }, - "description": "Sample for Decrypt", - "file": "cloudkms_v1_generated_key_management_service_decrypt_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_Decrypt_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_decrypt_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.destroy_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "DestroyCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest" - }, - { - "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.kms_v1.types.CryptoKeyVersion", - "shortName": "destroy_crypto_key_version" - }, - "description": "Sample for DestroyCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.destroy_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "DestroyCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.DestroyCryptoKeyVersionRequest" - }, - { - "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.kms_v1.types.CryptoKeyVersion", - "shortName": "destroy_crypto_key_version" - }, - "description": "Sample for DestroyCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_DestroyCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_destroy_crypto_key_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.encrypt", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.Encrypt", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "Encrypt" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.EncryptRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "plaintext", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.EncryptResponse", - "shortName": "encrypt" - }, - "description": "Sample for Encrypt", - "file": "cloudkms_v1_generated_key_management_service_encrypt_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_Encrypt_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_encrypt_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.encrypt", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.Encrypt", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "Encrypt" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.EncryptRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "plaintext", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.EncryptResponse", - "shortName": "encrypt" - }, - "description": "Sample for Encrypt", - "file": "cloudkms_v1_generated_key_management_service_encrypt_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_Encrypt_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_encrypt_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.generate_random_bytes", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GenerateRandomBytes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GenerateRandomBytesRequest" - }, - { - "name": "location", - "type": "str" - }, - { - "name": "length_bytes", - "type": "int" - }, - { - "name": "protection_level", - "type": "google.cloud.kms_v1.types.ProtectionLevel" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.GenerateRandomBytesResponse", - "shortName": "generate_random_bytes" - }, - "description": "Sample for GenerateRandomBytes", - "file": "cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_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": "cloudkms_v1_generated_key_management_service_generate_random_bytes_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.generate_random_bytes", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GenerateRandomBytes", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GenerateRandomBytes" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GenerateRandomBytesRequest" - }, - { - "name": "location", - "type": "str" - }, - { - "name": "length_bytes", - "type": "int" - }, - { - "name": "protection_level", - "type": "google.cloud.kms_v1.types.ProtectionLevel" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.GenerateRandomBytesResponse", - "shortName": "generate_random_bytes" - }, - "description": "Sample for GenerateRandomBytes", - "file": "cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_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": "cloudkms_v1_generated_key_management_service_generate_random_bytes_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.get_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GetCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetCryptoKeyVersionRequest" - }, - { - "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.kms_v1.types.CryptoKeyVersion", - "shortName": "get_crypto_key_version" - }, - "description": "Sample for GetCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_get_crypto_key_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.get_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GetCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GetCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetCryptoKeyVersionRequest" - }, - { - "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.kms_v1.types.CryptoKeyVersion", - "shortName": "get_crypto_key_version" - }, - "description": "Sample for GetCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GetCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_get_crypto_key_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.get_crypto_key", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GetCryptoKey", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GetCryptoKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetCryptoKeyRequest" - }, - { - "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.kms_v1.types.CryptoKey", - "shortName": "get_crypto_key" - }, - "description": "Sample for GetCryptoKey", - "file": "cloudkms_v1_generated_key_management_service_get_crypto_key_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GetCryptoKey_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": "cloudkms_v1_generated_key_management_service_get_crypto_key_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.get_crypto_key", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GetCryptoKey", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GetCryptoKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetCryptoKeyRequest" - }, - { - "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.kms_v1.types.CryptoKey", - "shortName": "get_crypto_key" - }, - "description": "Sample for GetCryptoKey", - "file": "cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GetCryptoKey_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": "cloudkms_v1_generated_key_management_service_get_crypto_key_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.get_import_job", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GetImportJob", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GetImportJob" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetImportJobRequest" - }, - { - "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.kms_v1.types.ImportJob", - "shortName": "get_import_job" - }, - "description": "Sample for GetImportJob", - "file": "cloudkms_v1_generated_key_management_service_get_import_job_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GetImportJob_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": "cloudkms_v1_generated_key_management_service_get_import_job_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.get_import_job", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GetImportJob", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GetImportJob" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetImportJobRequest" - }, - { - "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.kms_v1.types.ImportJob", - "shortName": "get_import_job" - }, - "description": "Sample for GetImportJob", - "file": "cloudkms_v1_generated_key_management_service_get_import_job_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GetImportJob_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": "cloudkms_v1_generated_key_management_service_get_import_job_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.get_key_ring", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GetKeyRing", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GetKeyRing" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetKeyRingRequest" - }, - { - "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.kms_v1.types.KeyRing", - "shortName": "get_key_ring" - }, - "description": "Sample for GetKeyRing", - "file": "cloudkms_v1_generated_key_management_service_get_key_ring_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GetKeyRing_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": "cloudkms_v1_generated_key_management_service_get_key_ring_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.get_key_ring", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GetKeyRing", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GetKeyRing" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetKeyRingRequest" - }, - { - "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.kms_v1.types.KeyRing", - "shortName": "get_key_ring" - }, - "description": "Sample for GetKeyRing", - "file": "cloudkms_v1_generated_key_management_service_get_key_ring_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GetKeyRing_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": "cloudkms_v1_generated_key_management_service_get_key_ring_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.get_public_key", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GetPublicKey", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GetPublicKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetPublicKeyRequest" - }, - { - "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.kms_v1.types.PublicKey", - "shortName": "get_public_key" - }, - "description": "Sample for GetPublicKey", - "file": "cloudkms_v1_generated_key_management_service_get_public_key_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GetPublicKey_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": "cloudkms_v1_generated_key_management_service_get_public_key_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.get_public_key", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.GetPublicKey", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "GetPublicKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.GetPublicKeyRequest" - }, - { - "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.kms_v1.types.PublicKey", - "shortName": "get_public_key" - }, - "description": "Sample for GetPublicKey", - "file": "cloudkms_v1_generated_key_management_service_get_public_key_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_GetPublicKey_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": "cloudkms_v1_generated_key_management_service_get_public_key_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.import_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "ImportCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.CryptoKeyVersion", - "shortName": "import_crypto_key_version" - }, - "description": "Sample for ImportCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_async", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.import_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "ImportCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ImportCryptoKeyVersionRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.CryptoKeyVersion", - "shortName": "import_crypto_key_version" - }, - "description": "Sample for ImportCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_ImportCryptoKeyVersion_sync", - "segments": [ - { - "end": 54, - "start": 27, - "type": "FULL" - }, - { - "end": 54, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 48, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 51, - "start": 49, - "type": "REQUEST_EXECUTION" - }, - { - "end": 55, - "start": 52, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.list_crypto_key_versions", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "ListCryptoKeyVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest" - }, - { - "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.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsAsyncPager", - "shortName": "list_crypto_key_versions" - }, - "description": "Sample for ListCryptoKeyVersions", - "file": "cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_list_crypto_key_versions_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.list_crypto_key_versions", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.ListCryptoKeyVersions", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "ListCryptoKeyVersions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListCryptoKeyVersionsRequest" - }, - { - "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.kms_v1.services.key_management_service.pagers.ListCryptoKeyVersionsPager", - "shortName": "list_crypto_key_versions" - }, - "description": "Sample for ListCryptoKeyVersions", - "file": "cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_ListCryptoKeyVersions_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_list_crypto_key_versions_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.list_crypto_keys", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.ListCryptoKeys", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "ListCryptoKeys" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListCryptoKeysRequest" - }, - { - "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.kms_v1.services.key_management_service.pagers.ListCryptoKeysAsyncPager", - "shortName": "list_crypto_keys" - }, - "description": "Sample for ListCryptoKeys", - "file": "cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_list_crypto_keys_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.list_crypto_keys", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.ListCryptoKeys", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "ListCryptoKeys" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListCryptoKeysRequest" - }, - { - "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.kms_v1.services.key_management_service.pagers.ListCryptoKeysPager", - "shortName": "list_crypto_keys" - }, - "description": "Sample for ListCryptoKeys", - "file": "cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_ListCryptoKeys_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_list_crypto_keys_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.list_import_jobs", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.ListImportJobs", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "ListImportJobs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListImportJobsRequest" - }, - { - "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.kms_v1.services.key_management_service.pagers.ListImportJobsAsyncPager", - "shortName": "list_import_jobs" - }, - "description": "Sample for ListImportJobs", - "file": "cloudkms_v1_generated_key_management_service_list_import_jobs_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_ListImportJobs_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_list_import_jobs_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.list_import_jobs", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.ListImportJobs", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "ListImportJobs" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListImportJobsRequest" - }, - { - "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.kms_v1.services.key_management_service.pagers.ListImportJobsPager", - "shortName": "list_import_jobs" - }, - "description": "Sample for ListImportJobs", - "file": "cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_ListImportJobs_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_list_import_jobs_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.list_key_rings", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.ListKeyRings", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "ListKeyRings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListKeyRingsRequest" - }, - { - "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.kms_v1.services.key_management_service.pagers.ListKeyRingsAsyncPager", - "shortName": "list_key_rings" - }, - "description": "Sample for ListKeyRings", - "file": "cloudkms_v1_generated_key_management_service_list_key_rings_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_ListKeyRings_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_list_key_rings_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.list_key_rings", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.ListKeyRings", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "ListKeyRings" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.ListKeyRingsRequest" - }, - { - "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.kms_v1.services.key_management_service.pagers.ListKeyRingsPager", - "shortName": "list_key_rings" - }, - "description": "Sample for ListKeyRings", - "file": "cloudkms_v1_generated_key_management_service_list_key_rings_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_ListKeyRings_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_list_key_rings_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.mac_sign", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.MacSign", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "MacSign" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.MacSignRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.MacSignResponse", - "shortName": "mac_sign" - }, - "description": "Sample for MacSign", - "file": "cloudkms_v1_generated_key_management_service_mac_sign_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_MacSign_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_mac_sign_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.mac_sign", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.MacSign", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "MacSign" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.MacSignRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.MacSignResponse", - "shortName": "mac_sign" - }, - "description": "Sample for MacSign", - "file": "cloudkms_v1_generated_key_management_service_mac_sign_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_MacSign_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_mac_sign_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.mac_verify", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.MacVerify", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "MacVerify" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.MacVerifyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "type": "bytes" - }, - { - "name": "mac", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.MacVerifyResponse", - "shortName": "mac_verify" - }, - "description": "Sample for MacVerify", - "file": "cloudkms_v1_generated_key_management_service_mac_verify_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_MacVerify_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_mac_verify_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.mac_verify", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.MacVerify", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "MacVerify" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.MacVerifyRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "data", - "type": "bytes" - }, - { - "name": "mac", - "type": "bytes" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.MacVerifyResponse", - "shortName": "mac_verify" - }, - "description": "Sample for MacVerify", - "file": "cloudkms_v1_generated_key_management_service_mac_verify_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_MacVerify_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_mac_verify_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.raw_decrypt", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.RawDecrypt", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "RawDecrypt" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.RawDecryptRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.RawDecryptResponse", - "shortName": "raw_decrypt" - }, - "description": "Sample for RawDecrypt", - "file": "cloudkms_v1_generated_key_management_service_raw_decrypt_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_RawDecrypt_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_raw_decrypt_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.raw_decrypt", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.RawDecrypt", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "RawDecrypt" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.RawDecryptRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.RawDecryptResponse", - "shortName": "raw_decrypt" - }, - "description": "Sample for RawDecrypt", - "file": "cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_RawDecrypt_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 47, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 50, - "start": 48, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_raw_decrypt_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.raw_encrypt", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.RawEncrypt", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "RawEncrypt" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.RawEncryptRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.RawEncryptResponse", - "shortName": "raw_encrypt" - }, - "description": "Sample for RawEncrypt", - "file": "cloudkms_v1_generated_key_management_service_raw_encrypt_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_RawEncrypt_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_raw_encrypt_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.raw_encrypt", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.RawEncrypt", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "RawEncrypt" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.RawEncryptRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.RawEncryptResponse", - "shortName": "raw_encrypt" - }, - "description": "Sample for RawEncrypt", - "file": "cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_RawEncrypt_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_raw_encrypt_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.restore_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "RestoreCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest" - }, - { - "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.kms_v1.types.CryptoKeyVersion", - "shortName": "restore_crypto_key_version" - }, - "description": "Sample for RestoreCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_restore_crypto_key_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.restore_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "RestoreCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.RestoreCryptoKeyVersionRequest" - }, - { - "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.kms_v1.types.CryptoKeyVersion", - "shortName": "restore_crypto_key_version" - }, - "description": "Sample for RestoreCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_RestoreCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_restore_crypto_key_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.update_crypto_key_primary_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "UpdateCryptoKeyPrimaryVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "crypto_key_version_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.CryptoKey", - "shortName": "update_crypto_key_primary_version" - }, - "description": "Sample for UpdateCryptoKeyPrimaryVersion", - "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_async", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.update_crypto_key_primary_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyPrimaryVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "UpdateCryptoKeyPrimaryVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateCryptoKeyPrimaryVersionRequest" - }, - { - "name": "name", - "type": "str" - }, - { - "name": "crypto_key_version_id", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.cloud.kms_v1.types.CryptoKey", - "shortName": "update_crypto_key_primary_version" - }, - "description": "Sample for UpdateCryptoKeyPrimaryVersion", - "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyPrimaryVersion_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "cloudkms_v1_generated_key_management_service_update_crypto_key_primary_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.update_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "UpdateCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest" - }, - { - "name": "crypto_key_version", - "type": "google.cloud.kms_v1.types.CryptoKeyVersion" - }, - { - "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.cloud.kms_v1.types.CryptoKeyVersion", - "shortName": "update_crypto_key_version" - }, - "description": "Sample for UpdateCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_update_crypto_key_version_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.update_crypto_key_version", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKeyVersion", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "UpdateCryptoKeyVersion" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateCryptoKeyVersionRequest" - }, - { - "name": "crypto_key_version", - "type": "google.cloud.kms_v1.types.CryptoKeyVersion" - }, - { - "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.cloud.kms_v1.types.CryptoKeyVersion", - "shortName": "update_crypto_key_version" - }, - "description": "Sample for UpdateCryptoKeyVersion", - "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_update_crypto_key_version_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", - "shortName": "KeyManagementServiceAsyncClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.update_crypto_key", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "UpdateCryptoKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateCryptoKeyRequest" - }, - { - "name": "crypto_key", - "type": "google.cloud.kms_v1.types.CryptoKey" - }, - { - "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.cloud.kms_v1.types.CryptoKey", - "shortName": "update_crypto_key" - }, - "description": "Sample for UpdateCryptoKey", - "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_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": "cloudkms_v1_generated_key_management_service_update_crypto_key_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", - "shortName": "KeyManagementServiceClient" - }, - "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.update_crypto_key", - "method": { - "fullName": "google.cloud.kms.v1.KeyManagementService.UpdateCryptoKey", - "service": { - "fullName": "google.cloud.kms.v1.KeyManagementService", - "shortName": "KeyManagementService" - }, - "shortName": "UpdateCryptoKey" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.kms_v1.types.UpdateCryptoKeyRequest" - }, - { - "name": "crypto_key", - "type": "google.cloud.kms_v1.types.CryptoKey" - }, - { - "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.cloud.kms_v1.types.CryptoKey", - "shortName": "update_crypto_key" - }, - "description": "Sample for UpdateCryptoKey", - "file": "cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "cloudkms_v1_generated_KeyManagementService_UpdateCryptoKey_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": "cloudkms_v1_generated_key_management_service_update_crypto_key_sync.py" - } - ] -} diff --git a/owl-bot-staging/google-cloud-kms/v1/scripts/fixup_kms_v1_keywords.py b/owl-bot-staging/google-cloud-kms/v1/scripts/fixup_kms_v1_keywords.py deleted file mode 100644 index 7a838e47d117..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/scripts/fixup_kms_v1_keywords.py +++ /dev/null @@ -1,219 +0,0 @@ -#! /usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class kmsCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'asymmetric_decrypt': ('name', 'ciphertext', 'ciphertext_crc32c', ), - 'asymmetric_sign': ('name', 'digest', 'digest_crc32c', 'data', 'data_crc32c', ), - 'create_crypto_key': ('parent', 'crypto_key_id', 'crypto_key', 'skip_initial_version_creation', ), - 'create_crypto_key_version': ('parent', 'crypto_key_version', ), - 'create_ekm_connection': ('parent', 'ekm_connection_id', 'ekm_connection', ), - 'create_import_job': ('parent', 'import_job_id', 'import_job', ), - 'create_key_handle': ('parent', 'key_handle', 'key_handle_id', ), - 'create_key_ring': ('parent', 'key_ring_id', 'key_ring', ), - 'decrypt': ('name', 'ciphertext', 'additional_authenticated_data', 'ciphertext_crc32c', 'additional_authenticated_data_crc32c', ), - 'destroy_crypto_key_version': ('name', ), - 'encrypt': ('name', 'plaintext', 'additional_authenticated_data', 'plaintext_crc32c', 'additional_authenticated_data_crc32c', ), - 'generate_random_bytes': ('location', 'length_bytes', 'protection_level', ), - 'get_autokey_config': ('name', ), - 'get_crypto_key': ('name', ), - 'get_crypto_key_version': ('name', ), - 'get_ekm_config': ('name', ), - 'get_ekm_connection': ('name', ), - 'get_import_job': ('name', ), - 'get_key_handle': ('name', ), - 'get_key_ring': ('name', ), - 'get_public_key': ('name', ), - 'import_crypto_key_version': ('parent', 'algorithm', 'import_job', 'crypto_key_version', 'wrapped_key', 'rsa_aes_wrapped_key', ), - 'list_crypto_keys': ('parent', 'page_size', 'page_token', 'version_view', 'filter', 'order_by', ), - 'list_crypto_key_versions': ('parent', 'page_size', 'page_token', 'view', 'filter', 'order_by', ), - 'list_ekm_connections': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_import_jobs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_key_handles': ('parent', 'page_size', 'page_token', 'filter', ), - 'list_key_rings': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'mac_sign': ('name', 'data', 'data_crc32c', ), - 'mac_verify': ('name', 'data', 'mac', 'data_crc32c', 'mac_crc32c', ), - 'raw_decrypt': ('name', 'ciphertext', 'initialization_vector', 'additional_authenticated_data', 'tag_length', 'ciphertext_crc32c', 'additional_authenticated_data_crc32c', 'initialization_vector_crc32c', ), - 'raw_encrypt': ('name', 'plaintext', 'additional_authenticated_data', 'plaintext_crc32c', 'additional_authenticated_data_crc32c', 'initialization_vector', 'initialization_vector_crc32c', ), - 'restore_crypto_key_version': ('name', ), - 'show_effective_autokey_config': ('parent', ), - 'update_autokey_config': ('autokey_config', 'update_mask', ), - 'update_crypto_key': ('crypto_key', 'update_mask', ), - 'update_crypto_key_primary_version': ('name', 'crypto_key_version_id', ), - 'update_crypto_key_version': ('crypto_key_version', 'update_mask', ), - 'update_ekm_config': ('ekm_config', 'update_mask', ), - 'update_ekm_connection': ('ekm_connection', 'update_mask', ), - 'verify_connectivity': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - } - - 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=kmsCallTransformer(), -): - """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 kms 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-kms/v1/setup.py b/owl-bot-staging/google-cloud-kms/v1/setup.py deleted file mode 100644 index 151f2d829c6b..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/setup.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import io -import os -import re - -import setuptools # type: ignore - -package_root = os.path.abspath(os.path.dirname(__file__)) - -name = 'google-cloud-kms' - - -description = "Google Cloud Kms API client library" - -version = None - -with open(os.path.join(package_root, 'google/cloud/kms/gapic_version.py')) as fp: - version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) - assert (len(version_candidates) == 1) - version = version_candidates[0] - -if version[0] == "0": - release_status = "Development Status :: 4 - Beta" -else: - release_status = "Development Status :: 5 - Production/Stable" - -dependencies = [ - "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", - # Exclude incompatible versions of `google-auth` - # See https://github.com/googleapis/google-cloud-python/issues/12364 - "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", - "proto-plus >= 1.22.3, <2.0.0dev", - "proto-plus >= 1.25.0, <2.0.0dev; python_version >= '3.13'", - "protobuf>=3.20.2,<6.0.0dev,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", - "grpc-google-iam-v1 >= 0.12.4, <1.0.0dev", -] -extras = { -} -url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-kms" - -package_root = os.path.abspath(os.path.dirname(__file__)) - -readme_filename = os.path.join(package_root, "README.rst") -with io.open(readme_filename, encoding="utf-8") as readme_file: - readme = readme_file.read() - -packages = [ - package - for package in setuptools.find_namespace_packages() - if package.startswith("google") -] - -setuptools.setup( - name=name, - version=version, - description=description, - long_description=readme, - author="Google LLC", - author_email="googleapis-packages@google.com", - license="Apache 2.0", - url=url, - classifiers=[ - release_status, - "Intended Audience :: Developers", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", - "Operating System :: OS Independent", - "Topic :: Internet", - ], - platforms="Posix; MacOS X; Windows", - packages=packages, - python_requires=">=3.7", - install_requires=dependencies, - extras_require=extras, - include_package_data=True, - zip_safe=False, -) diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.10.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.10.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.10.txt +++ /dev/null @@ -1,7 +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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.11.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.11.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.11.txt +++ /dev/null @@ -1,7 +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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.12.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.12.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.12.txt +++ /dev/null @@ -1,7 +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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.13.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.13.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.13.txt +++ /dev/null @@ -1,7 +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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.7.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.7.txt deleted file mode 100644 index a81fb6bcd05c..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.7.txt +++ /dev/null @@ -1,11 +0,0 @@ -# This constraints file is used to check that lower bounds -# are correct in setup.py -# List all library dependencies and extras in this file. -# Pin the version to the lower bound. -# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", -# Then this file should have google-cloud-foo==1.14.0 -google-api-core==1.34.1 -google-auth==2.14.1 -proto-plus==1.22.3 -protobuf==3.20.2 -grpc-google-iam-v1==0.12.4 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.8.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.8.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.8.txt +++ /dev/null @@ -1,7 +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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.9.txt b/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.9.txt deleted file mode 100644 index ad3f0fa58e2d..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/testing/constraints-3.9.txt +++ /dev/null @@ -1,7 +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 -grpc-google-iam-v1 diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/__init__.py b/owl-bot-staging/google-cloud-kms/v1/tests/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/tests/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/__init__.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/tests/unit/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/__init__.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/__init__.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/__init__.py deleted file mode 100644 index 7b3de3117f38..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ - -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey.py deleted file mode 100644 index f1c8bcb11842..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey.py +++ /dev/null @@ -1,5012 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.kms_v1.services.autokey import AutokeyAsyncClient -from google.cloud.kms_v1.services.autokey import AutokeyClient -from google.cloud.kms_v1.services.autokey import pagers -from google.cloud.kms_v1.services.autokey import transports -from google.cloud.kms_v1.types import autokey -from google.cloud.location import locations_pb2 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -import google.auth - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert AutokeyClient._get_default_mtls_endpoint(None) is None - assert AutokeyClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AutokeyClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AutokeyClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AutokeyClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AutokeyClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AutokeyClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AutokeyClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AutokeyClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AutokeyClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert AutokeyClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AutokeyClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AutokeyClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AutokeyClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert AutokeyClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert AutokeyClient._get_client_cert_source(None, False) is None - assert AutokeyClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AutokeyClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert AutokeyClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AutokeyClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AutokeyClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyClient)) -@mock.patch.object(AutokeyAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AutokeyClient._DEFAULT_UNIVERSE - default_endpoint = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AutokeyClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AutokeyClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutokeyClient.DEFAULT_MTLS_ENDPOINT - assert AutokeyClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AutokeyClient._get_api_endpoint(None, None, default_universe, "always") == AutokeyClient.DEFAULT_MTLS_ENDPOINT - assert AutokeyClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutokeyClient.DEFAULT_MTLS_ENDPOINT - assert AutokeyClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AutokeyClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AutokeyClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert AutokeyClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AutokeyClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AutokeyClient._get_universe_domain(None, None) == AutokeyClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AutokeyClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AutokeyClient, "grpc"), - (AutokeyAsyncClient, "grpc_asyncio"), - (AutokeyClient, "rest"), -]) -def test_autokey_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 == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudkms.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AutokeyGrpcTransport, "grpc"), - (transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AutokeyRestTransport, "rest"), -]) -def test_autokey_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", [ - (AutokeyClient, "grpc"), - (AutokeyAsyncClient, "grpc_asyncio"), - (AutokeyClient, "rest"), -]) -def test_autokey_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 == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudkms.googleapis.com' - ) - - -def test_autokey_client_get_transport_class(): - transport = AutokeyClient.get_transport_class() - available_transports = [ - transports.AutokeyGrpcTransport, - transports.AutokeyRestTransport, - ] - assert transport in available_transports - - transport = AutokeyClient.get_transport_class("grpc") - assert transport == transports.AutokeyGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AutokeyClient, transports.AutokeyGrpcTransport, "grpc"), - (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio"), - (AutokeyClient, transports.AutokeyRestTransport, "rest"), -]) -@mock.patch.object(AutokeyClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyClient)) -@mock.patch.object(AutokeyAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAsyncClient)) -def test_autokey_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(AutokeyClient, '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(AutokeyClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AutokeyClient, transports.AutokeyGrpcTransport, "grpc", "true"), - (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AutokeyClient, transports.AutokeyGrpcTransport, "grpc", "false"), - (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AutokeyClient, transports.AutokeyRestTransport, "rest", "true"), - (AutokeyClient, transports.AutokeyRestTransport, "rest", "false"), -]) -@mock.patch.object(AutokeyClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyClient)) -@mock.patch.object(AutokeyAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_autokey_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - AutokeyClient, AutokeyAsyncClient -]) -@mock.patch.object(AutokeyClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutokeyClient)) -@mock.patch.object(AutokeyAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutokeyAsyncClient)) -def test_autokey_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - AutokeyClient, AutokeyAsyncClient -]) -@mock.patch.object(AutokeyClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyClient)) -@mock.patch.object(AutokeyAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAsyncClient)) -def test_autokey_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AutokeyClient._DEFAULT_UNIVERSE - default_endpoint = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AutokeyClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AutokeyClient, transports.AutokeyGrpcTransport, "grpc"), - (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio"), - (AutokeyClient, transports.AutokeyRestTransport, "rest"), -]) -def test_autokey_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AutokeyClient, transports.AutokeyGrpcTransport, "grpc", grpc_helpers), - (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AutokeyClient, transports.AutokeyRestTransport, "rest", None), -]) -def test_autokey_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_autokey_client_client_options_from_dict(): - with mock.patch('google.cloud.kms_v1.services.autokey.transports.AutokeyGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AutokeyClient( - 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", [ - (AutokeyClient, transports.AutokeyGrpcTransport, "grpc", grpc_helpers), - (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_autokey_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudkms.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - scopes=None, - default_host="cloudkms.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - autokey.CreateKeyHandleRequest, - dict, -]) -def test_create_key_handle(request_type, transport: str = 'grpc'): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_key_handle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name='operations/spam') - response = client.create_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = autokey.CreateKeyHandleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_create_key_handle_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = autokey.CreateKeyHandleRequest( - parent='parent_value', - key_handle_id='key_handle_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_handle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_key_handle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == autokey.CreateKeyHandleRequest( - parent='parent_value', - key_handle_id='key_handle_id_value', - ) - -def test_create_key_handle_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_key_handle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_key_handle] = mock_rpc - request = {} - client.create_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_key_handle(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_key_handle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_key_handle in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_key_handle] = mock_rpc - - request = {} - await client.create_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.create_key_handle(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_key_handle_async(transport: str = 'grpc_asyncio', request_type=autokey.CreateKeyHandleRequest): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_handle), - '__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_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = autokey.CreateKeyHandleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_create_key_handle_async_from_dict(): - await test_create_key_handle_async(request_type=dict) - -def test_create_key_handle_field_headers(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey.CreateKeyHandleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_handle), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_key_handle_field_headers_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey.CreateKeyHandleRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_handle), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(operations_pb2.Operation(name='operations/op')) - await client.create_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_key_handle_flattened(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_handle), - '__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_key_handle( - parent='parent_value', - key_handle=autokey.KeyHandle(name='name_value'), - key_handle_id='key_handle_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].key_handle - mock_val = autokey.KeyHandle(name='name_value') - assert arg == mock_val - arg = args[0].key_handle_id - mock_val = 'key_handle_id_value' - assert arg == mock_val - - -def test_create_key_handle_flattened_error(): - client = AutokeyClient( - credentials=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_key_handle( - autokey.CreateKeyHandleRequest(), - parent='parent_value', - key_handle=autokey.KeyHandle(name='name_value'), - key_handle_id='key_handle_id_value', - ) - -@pytest.mark.asyncio -async def test_create_key_handle_flattened_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_handle), - '__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_key_handle( - parent='parent_value', - key_handle=autokey.KeyHandle(name='name_value'), - key_handle_id='key_handle_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = 'parent_value' - assert arg == mock_val - arg = args[0].key_handle - mock_val = autokey.KeyHandle(name='name_value') - assert arg == mock_val - arg = args[0].key_handle_id - mock_val = 'key_handle_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_key_handle_flattened_error_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_key_handle( - autokey.CreateKeyHandleRequest(), - parent='parent_value', - key_handle=autokey.KeyHandle(name='name_value'), - key_handle_id='key_handle_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - autokey.GetKeyHandleRequest, - dict, -]) -def test_get_key_handle(request_type, transport: str = 'grpc'): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_key_handle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey.KeyHandle( - name='name_value', - kms_key='kms_key_value', - resource_type_selector='resource_type_selector_value', - ) - response = client.get_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = autokey.GetKeyHandleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey.KeyHandle) - assert response.name == 'name_value' - assert response.kms_key == 'kms_key_value' - assert response.resource_type_selector == 'resource_type_selector_value' - - -def test_get_key_handle_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = autokey.GetKeyHandleRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_handle), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_key_handle(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == autokey.GetKeyHandleRequest( - name='name_value', - ) - -def test_get_key_handle_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_key_handle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_key_handle] = mock_rpc - request = {} - client.get_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_key_handle(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_key_handle_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_key_handle in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_key_handle] = mock_rpc - - request = {} - await client.get_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_key_handle(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_key_handle_async(transport: str = 'grpc_asyncio', request_type=autokey.GetKeyHandleRequest): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_handle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autokey.KeyHandle( - name='name_value', - kms_key='kms_key_value', - resource_type_selector='resource_type_selector_value', - )) - response = await client.get_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = autokey.GetKeyHandleRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey.KeyHandle) - assert response.name == 'name_value' - assert response.kms_key == 'kms_key_value' - assert response.resource_type_selector == 'resource_type_selector_value' - - -@pytest.mark.asyncio -async def test_get_key_handle_async_from_dict(): - await test_get_key_handle_async(request_type=dict) - -def test_get_key_handle_field_headers(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey.GetKeyHandleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_handle), - '__call__') as call: - call.return_value = autokey.KeyHandle() - client.get_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_key_handle_field_headers_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey.GetKeyHandleRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_handle), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.KeyHandle()) - await client.get_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_key_handle_flattened(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_handle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey.KeyHandle() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_key_handle( - 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_key_handle_flattened_error(): - client = AutokeyClient( - credentials=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_key_handle( - autokey.GetKeyHandleRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_key_handle_flattened_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_handle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey.KeyHandle() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.KeyHandle()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_key_handle( - 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_key_handle_flattened_error_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_key_handle( - autokey.GetKeyHandleRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - autokey.ListKeyHandlesRequest, - dict, -]) -def test_list_key_handles(request_type, transport: str = 'grpc'): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_key_handles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey.ListKeyHandlesResponse( - next_page_token='next_page_token_value', - ) - response = client.list_key_handles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = autokey.ListKeyHandlesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKeyHandlesPager) - assert response.next_page_token == 'next_page_token_value' - - -def test_list_key_handles_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = autokey.ListKeyHandlesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_handles), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_key_handles(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == autokey.ListKeyHandlesRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - ) - -def test_list_key_handles_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_key_handles in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_key_handles] = mock_rpc - request = {} - client.list_key_handles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_key_handles(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_key_handles_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_key_handles in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_key_handles] = mock_rpc - - request = {} - await client.list_key_handles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_key_handles(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_key_handles_async(transport: str = 'grpc_asyncio', request_type=autokey.ListKeyHandlesRequest): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_handles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autokey.ListKeyHandlesResponse( - next_page_token='next_page_token_value', - )) - response = await client.list_key_handles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = autokey.ListKeyHandlesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKeyHandlesAsyncPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.asyncio -async def test_list_key_handles_async_from_dict(): - await test_list_key_handles_async(request_type=dict) - -def test_list_key_handles_field_headers(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey.ListKeyHandlesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_handles), - '__call__') as call: - call.return_value = autokey.ListKeyHandlesResponse() - client.list_key_handles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_key_handles_field_headers_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey.ListKeyHandlesRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_handles), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.ListKeyHandlesResponse()) - await client.list_key_handles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_key_handles_flattened(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_handles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey.ListKeyHandlesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_key_handles( - 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_key_handles_flattened_error(): - client = AutokeyClient( - credentials=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_key_handles( - autokey.ListKeyHandlesRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_key_handles_flattened_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_handles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey.ListKeyHandlesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.ListKeyHandlesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_key_handles( - 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_key_handles_flattened_error_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_key_handles( - autokey.ListKeyHandlesRequest(), - parent='parent_value', - ) - - -def test_list_key_handles_pager(transport_name: str = "grpc"): - client = AutokeyClient( - 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_key_handles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - autokey.KeyHandle(), - autokey.KeyHandle(), - ], - next_page_token='abc', - ), - autokey.ListKeyHandlesResponse( - key_handles=[], - next_page_token='def', - ), - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - ], - next_page_token='ghi', - ), - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - autokey.KeyHandle(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_key_handles(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, autokey.KeyHandle) - for i in results) -def test_list_key_handles_pages(transport_name: str = "grpc"): - client = AutokeyClient( - 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_key_handles), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - autokey.KeyHandle(), - autokey.KeyHandle(), - ], - next_page_token='abc', - ), - autokey.ListKeyHandlesResponse( - key_handles=[], - next_page_token='def', - ), - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - ], - next_page_token='ghi', - ), - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - autokey.KeyHandle(), - ], - ), - RuntimeError, - ) - pages = list(client.list_key_handles(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_key_handles_async_pager(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_handles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - autokey.KeyHandle(), - autokey.KeyHandle(), - ], - next_page_token='abc', - ), - autokey.ListKeyHandlesResponse( - key_handles=[], - next_page_token='def', - ), - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - ], - next_page_token='ghi', - ), - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - autokey.KeyHandle(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_key_handles(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, autokey.KeyHandle) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_key_handles_async_pages(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_handles), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - autokey.KeyHandle(), - autokey.KeyHandle(), - ], - next_page_token='abc', - ), - autokey.ListKeyHandlesResponse( - key_handles=[], - next_page_token='def', - ), - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - ], - next_page_token='ghi', - ), - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - autokey.KeyHandle(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_key_handles(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_create_key_handle_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_key_handle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_key_handle] = mock_rpc - - request = {} - client.create_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.create_key_handle(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_key_handle_rest_required_fields(request_type=autokey.CreateKeyHandleRequest): - transport_class = transports.AutokeyRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_key_handle._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_key_handle._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("key_handle_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_key_handle(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_key_handle_rest_unset_required_fields(): - transport = transports.AutokeyRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_key_handle._get_unset_required_fields({}) - assert set(unset_fields) == (set(("keyHandleId", )) & set(("parent", "keyHandle", ))) - - -def test_create_key_handle_rest_flattened(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.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', - key_handle=autokey.KeyHandle(name='name_value'), - key_handle_id='key_handle_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_key_handle(**mock_args) - - # Establish that the underlying call 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/*}/keyHandles" % client.transport._host, args[1]) - - -def test_create_key_handle_rest_flattened_error(transport: str = 'rest'): - client = AutokeyClient( - credentials=ga_credentials.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_key_handle( - autokey.CreateKeyHandleRequest(), - parent='parent_value', - key_handle=autokey.KeyHandle(name='name_value'), - key_handle_id='key_handle_id_value', - ) - - -def test_get_key_handle_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_key_handle in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_key_handle] = mock_rpc - - request = {} - client.get_key_handle(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_key_handle(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_key_handle_rest_required_fields(request_type=autokey.GetKeyHandleRequest): - transport_class = transports.AutokeyRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_key_handle._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_key_handle._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = autokey.KeyHandle() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = autokey.KeyHandle.pb(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_key_handle(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_key_handle_rest_unset_required_fields(): - transport = transports.AutokeyRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_key_handle._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_key_handle_rest_flattened(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = autokey.KeyHandle() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyHandles/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = autokey.KeyHandle.pb(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_key_handle(**mock_args) - - # Establish that the underlying call 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/*/keyHandles/*}" % client.transport._host, args[1]) - - -def test_get_key_handle_rest_flattened_error(transport: str = 'rest'): - client = AutokeyClient( - credentials=ga_credentials.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_key_handle( - autokey.GetKeyHandleRequest(), - name='name_value', - ) - - -def test_list_key_handles_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_key_handles in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_key_handles] = mock_rpc - - request = {} - client.list_key_handles(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_key_handles(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_key_handles_rest_required_fields(request_type=autokey.ListKeyHandlesRequest): - transport_class = transports.AutokeyRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_key_handles._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_key_handles._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = autokey.ListKeyHandlesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = autokey.ListKeyHandlesResponse.pb(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_key_handles(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_key_handles_rest_unset_required_fields(): - transport = transports.AutokeyRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_key_handles._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_key_handles_rest_flattened(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = autokey.ListKeyHandlesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = autokey.ListKeyHandlesResponse.pb(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_key_handles(**mock_args) - - # Establish that the underlying call 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/*}/keyHandles" % client.transport._host, args[1]) - - -def test_list_key_handles_rest_flattened_error(transport: str = 'rest'): - client = AutokeyClient( - credentials=ga_credentials.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_key_handles( - autokey.ListKeyHandlesRequest(), - parent='parent_value', - ) - - -def test_list_key_handles_rest_pager(transport: str = 'rest'): - client = AutokeyClient( - 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 = ( - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - autokey.KeyHandle(), - autokey.KeyHandle(), - ], - next_page_token='abc', - ), - autokey.ListKeyHandlesResponse( - key_handles=[], - next_page_token='def', - ), - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - ], - next_page_token='ghi', - ), - autokey.ListKeyHandlesResponse( - key_handles=[ - autokey.KeyHandle(), - autokey.KeyHandle(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(autokey.ListKeyHandlesResponse.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_key_handles(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, autokey.KeyHandle) - for i in results) - - pages = list(client.list_key_handles(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.AutokeyGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AutokeyGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutokeyClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AutokeyGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AutokeyClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AutokeyClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AutokeyGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutokeyClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AutokeyGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AutokeyClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AutokeyGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AutokeyGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AutokeyGrpcTransport, - transports.AutokeyGrpcAsyncIOTransport, - transports.AutokeyRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = AutokeyClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_key_handle_empty_call_grpc(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_key_handle), - '__call__') as call: - call.return_value = operations_pb2.Operation(name='operations/op') - client.create_key_handle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey.CreateKeyHandleRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_key_handle_empty_call_grpc(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_key_handle), - '__call__') as call: - call.return_value = autokey.KeyHandle() - client.get_key_handle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey.GetKeyHandleRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_key_handles_empty_call_grpc(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_key_handles), - '__call__') as call: - call.return_value = autokey.ListKeyHandlesResponse() - client.list_key_handles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey.ListKeyHandlesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AutokeyAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_key_handle_empty_call_grpc_asyncio(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_key_handle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name='operations/spam') - ) - await client.create_key_handle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey.CreateKeyHandleRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_key_handle_empty_call_grpc_asyncio(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_key_handle), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.KeyHandle( - name='name_value', - kms_key='kms_key_value', - resource_type_selector='resource_type_selector_value', - )) - await client.get_key_handle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey.GetKeyHandleRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_key_handles_empty_call_grpc_asyncio(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_key_handles), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey.ListKeyHandlesResponse( - next_page_token='next_page_token_value', - )) - await client.list_key_handles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey.ListKeyHandlesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AutokeyClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_create_key_handle_rest_bad_request(request_type=autokey.CreateKeyHandleRequest): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.create_key_handle(request) - - -@pytest.mark.parametrize("request_type", [ - autokey.CreateKeyHandleRequest, - dict, -]) -def test_create_key_handle_rest_call_success(request_type): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["key_handle"] = {'name': 'name_value', 'kms_key': 'kms_key_value', 'resource_type_selector': 'resource_type_selector_value'} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = autokey.CreateKeyHandleRequest.meta.fields["key_handle"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["key_handle"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["key_handle"][field])): - del request_init["key_handle"][field][i][subfield] - else: - del request_init["key_handle"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name='operations/spam') - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_key_handle(request) - - # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_key_handle_rest_interceptors(null_interceptor): - transport = transports.AutokeyRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutokeyRestInterceptor(), - ) - client = AutokeyClient(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.AutokeyRestInterceptor, "post_create_key_handle") as post, \ - mock.patch.object(transports.AutokeyRestInterceptor, "pre_create_key_handle") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = autokey.CreateKeyHandleRequest.pb(autokey.CreateKeyHandleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) - req.return_value.content = return_value - - request = autokey.CreateKeyHandleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - - client.create_key_handle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_key_handle_rest_bad_request(request_type=autokey.GetKeyHandleRequest): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyHandles/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_key_handle(request) - - -@pytest.mark.parametrize("request_type", [ - autokey.GetKeyHandleRequest, - dict, -]) -def test_get_key_handle_rest_call_success(request_type): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyHandles/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = autokey.KeyHandle( - name='name_value', - kms_key='kms_key_value', - resource_type_selector='resource_type_selector_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = autokey.KeyHandle.pb(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_key_handle(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey.KeyHandle) - assert response.name == 'name_value' - assert response.kms_key == 'kms_key_value' - assert response.resource_type_selector == 'resource_type_selector_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_key_handle_rest_interceptors(null_interceptor): - transport = transports.AutokeyRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutokeyRestInterceptor(), - ) - client = AutokeyClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AutokeyRestInterceptor, "post_get_key_handle") as post, \ - mock.patch.object(transports.AutokeyRestInterceptor, "pre_get_key_handle") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = autokey.GetKeyHandleRequest.pb(autokey.GetKeyHandleRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = autokey.KeyHandle.to_json(autokey.KeyHandle()) - req.return_value.content = return_value - - request = autokey.GetKeyHandleRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = autokey.KeyHandle() - - client.get_key_handle(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_key_handles_rest_bad_request(request_type=autokey.ListKeyHandlesRequest): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_key_handles(request) - - -@pytest.mark.parametrize("request_type", [ - autokey.ListKeyHandlesRequest, - dict, -]) -def test_list_key_handles_rest_call_success(request_type): - client = AutokeyClient( - 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 = autokey.ListKeyHandlesResponse( - next_page_token='next_page_token_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = autokey.ListKeyHandlesResponse.pb(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_key_handles(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKeyHandlesPager) - assert response.next_page_token == 'next_page_token_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_key_handles_rest_interceptors(null_interceptor): - transport = transports.AutokeyRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutokeyRestInterceptor(), - ) - client = AutokeyClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AutokeyRestInterceptor, "post_list_key_handles") as post, \ - mock.patch.object(transports.AutokeyRestInterceptor, "pre_list_key_handles") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = autokey.ListKeyHandlesRequest.pb(autokey.ListKeyHandlesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = autokey.ListKeyHandlesResponse.to_json(autokey.ListKeyHandlesResponse()) - req.return_value.content = return_value - - request = autokey.ListKeyHandlesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = autokey.ListKeyHandlesResponse() - - client.list_key_handles(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_initialize_client_w_rest(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_key_handle_empty_call_rest(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_key_handle), - '__call__') as call: - client.create_key_handle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey.CreateKeyHandleRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_key_handle_empty_call_rest(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_key_handle), - '__call__') as call: - client.get_key_handle(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey.GetKeyHandleRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_key_handles_empty_call_rest(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_key_handles), - '__call__') as call: - client.list_key_handles(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey.ListKeyHandlesRequest() - - assert args[0] == request_msg - - -def test_autokey_rest_lro_client(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - transport = client.transport - - # Ensure that we have an api-core operations client. - assert isinstance( - transport.operations_client, -operations_v1.AbstractOperationsClient, - ) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AutokeyGrpcTransport, - ) - -def test_autokey_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AutokeyTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_autokey_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.kms_v1.services.autokey.transports.AutokeyTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AutokeyTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'create_key_handle', - 'get_key_handle', - 'list_key_handles', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - ) - 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_autokey_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.kms_v1.services.autokey.transports.AutokeyTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AutokeyTransport( - 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', - 'https://www.googleapis.com/auth/cloudkms', -), - quota_project_id="octopus", - ) - - -def test_autokey_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.kms_v1.services.autokey.transports.AutokeyTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AutokeyTransport() - adc.assert_called_once() - - -def test_autokey_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) - AutokeyClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AutokeyGrpcTransport, - transports.AutokeyGrpcAsyncIOTransport, - ], -) -def test_autokey_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', 'https://www.googleapis.com/auth/cloudkms',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AutokeyGrpcTransport, - transports.AutokeyGrpcAsyncIOTransport, - transports.AutokeyRestTransport, - ], -) -def test_autokey_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.AutokeyGrpcTransport, grpc_helpers), - (transports.AutokeyGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_autokey_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( - "cloudkms.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - scopes=["1", "2"], - default_host="cloudkms.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AutokeyGrpcTransport, transports.AutokeyGrpcAsyncIOTransport]) -def test_autokey_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_autokey_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.AutokeyRestTransport ( - 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_autokey_host_no_port(transport_name): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudkms.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_autokey_host_with_port(transport_name): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudkms.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudkms.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_autokey_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AutokeyClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AutokeyClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.create_key_handle._session - session2 = client2.transport.create_key_handle._session - assert session1 != session2 - session1 = client1.transport.get_key_handle._session - session2 = client2.transport.get_key_handle._session - assert session1 != session2 - session1 = client1.transport.list_key_handles._session - session2 = client2.transport.list_key_handles._session - assert session1 != session2 -def test_autokey_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AutokeyGrpcTransport( - 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_autokey_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AutokeyGrpcAsyncIOTransport( - 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.AutokeyGrpcTransport, transports.AutokeyGrpcAsyncIOTransport]) -def test_autokey_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.AutokeyGrpcTransport, transports.AutokeyGrpcAsyncIOTransport]) -def test_autokey_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_autokey_grpc_lro_client(): - client = AutokeyClient( - 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_autokey_grpc_lro_async_client(): - client = AutokeyAsyncClient( - 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_crypto_key_path(): - project = "squid" - location = "clam" - key_ring = "whelk" - crypto_key = "octopus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - actual = AutokeyClient.crypto_key_path(project, location, key_ring, crypto_key) - assert expected == actual - - -def test_parse_crypto_key_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "key_ring": "cuttlefish", - "crypto_key": "mussel", - } - path = AutokeyClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyClient.parse_crypto_key_path(path) - assert expected == actual - -def test_key_handle_path(): - project = "winkle" - location = "nautilus" - key_handle = "scallop" - expected = "projects/{project}/locations/{location}/keyHandles/{key_handle}".format(project=project, location=location, key_handle=key_handle, ) - actual = AutokeyClient.key_handle_path(project, location, key_handle) - assert expected == actual - - -def test_parse_key_handle_path(): - expected = { - "project": "abalone", - "location": "squid", - "key_handle": "clam", - } - path = AutokeyClient.key_handle_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyClient.parse_key_handle_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AutokeyClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = AutokeyClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = AutokeyClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = AutokeyClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AutokeyClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = AutokeyClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = AutokeyClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = AutokeyClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AutokeyClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = AutokeyClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyClient.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.AutokeyTransport, '_prep_wrapped_messages') as prep: - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AutokeyTransport, '_prep_wrapped_messages') as prep: - transport_class = AutokeyClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_get_operation(transport: str = "grpc"): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = AutokeyClient( - 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 = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc_asyncio"): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -def test_get_iam_policy(transport: str = "grpc"): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = "grpc"): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = AutokeyAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = AutokeyClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = AutokeyClient( - 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", [ - (AutokeyClient, transports.AutokeyGrpcTransport), - (AutokeyAsyncClient, transports.AutokeyGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey_admin.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey_admin.py deleted file mode 100644 index 64ab5f6a03e9..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_autokey_admin.py +++ /dev/null @@ -1,4652 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.kms_v1.services.autokey_admin import AutokeyAdminAsyncClient -from google.cloud.kms_v1.services.autokey_admin import AutokeyAdminClient -from google.cloud.kms_v1.services.autokey_admin import transports -from google.cloud.kms_v1.types import autokey_admin -from google.cloud.location import locations_pb2 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -import google.auth - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert AutokeyAdminClient._get_default_mtls_endpoint(None) is None - assert AutokeyAdminClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert AutokeyAdminClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert AutokeyAdminClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert AutokeyAdminClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert AutokeyAdminClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert AutokeyAdminClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert AutokeyAdminClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert AutokeyAdminClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - AutokeyAdminClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert AutokeyAdminClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert AutokeyAdminClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert AutokeyAdminClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - AutokeyAdminClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert AutokeyAdminClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert AutokeyAdminClient._get_client_cert_source(None, False) is None - assert AutokeyAdminClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert AutokeyAdminClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert AutokeyAdminClient._get_client_cert_source(None, True) is mock_default_cert_source - assert AutokeyAdminClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(AutokeyAdminClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminClient)) -@mock.patch.object(AutokeyAdminAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = AutokeyAdminClient._DEFAULT_UNIVERSE - default_endpoint = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert AutokeyAdminClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert AutokeyAdminClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == AutokeyAdminClient.DEFAULT_MTLS_ENDPOINT - assert AutokeyAdminClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert AutokeyAdminClient._get_api_endpoint(None, None, default_universe, "always") == AutokeyAdminClient.DEFAULT_MTLS_ENDPOINT - assert AutokeyAdminClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == AutokeyAdminClient.DEFAULT_MTLS_ENDPOINT - assert AutokeyAdminClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert AutokeyAdminClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - AutokeyAdminClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert AutokeyAdminClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert AutokeyAdminClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert AutokeyAdminClient._get_universe_domain(None, None) == AutokeyAdminClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - AutokeyAdminClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (AutokeyAdminClient, "grpc"), - (AutokeyAdminAsyncClient, "grpc_asyncio"), - (AutokeyAdminClient, "rest"), -]) -def test_autokey_admin_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 == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudkms.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.AutokeyAdminGrpcTransport, "grpc"), - (transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.AutokeyAdminRestTransport, "rest"), -]) -def test_autokey_admin_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", [ - (AutokeyAdminClient, "grpc"), - (AutokeyAdminAsyncClient, "grpc_asyncio"), - (AutokeyAdminClient, "rest"), -]) -def test_autokey_admin_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 == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudkms.googleapis.com' - ) - - -def test_autokey_admin_client_get_transport_class(): - transport = AutokeyAdminClient.get_transport_class() - available_transports = [ - transports.AutokeyAdminGrpcTransport, - transports.AutokeyAdminRestTransport, - ] - assert transport in available_transports - - transport = AutokeyAdminClient.get_transport_class("grpc") - assert transport == transports.AutokeyAdminGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc"), - (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio"), - (AutokeyAdminClient, transports.AutokeyAdminRestTransport, "rest"), -]) -@mock.patch.object(AutokeyAdminClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminClient)) -@mock.patch.object(AutokeyAdminAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminAsyncClient)) -def test_autokey_admin_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(AutokeyAdminClient, '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(AutokeyAdminClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc", "true"), - (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc", "false"), - (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (AutokeyAdminClient, transports.AutokeyAdminRestTransport, "rest", "true"), - (AutokeyAdminClient, transports.AutokeyAdminRestTransport, "rest", "false"), -]) -@mock.patch.object(AutokeyAdminClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminClient)) -@mock.patch.object(AutokeyAdminAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_autokey_admin_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - AutokeyAdminClient, AutokeyAdminAsyncClient -]) -@mock.patch.object(AutokeyAdminClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutokeyAdminClient)) -@mock.patch.object(AutokeyAdminAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AutokeyAdminAsyncClient)) -def test_autokey_admin_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - AutokeyAdminClient, AutokeyAdminAsyncClient -]) -@mock.patch.object(AutokeyAdminClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminClient)) -@mock.patch.object(AutokeyAdminAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(AutokeyAdminAsyncClient)) -def test_autokey_admin_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = AutokeyAdminClient._DEFAULT_UNIVERSE - default_endpoint = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = AutokeyAdminClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc"), - (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio"), - (AutokeyAdminClient, transports.AutokeyAdminRestTransport, "rest"), -]) -def test_autokey_admin_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc", grpc_helpers), - (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (AutokeyAdminClient, transports.AutokeyAdminRestTransport, "rest", None), -]) -def test_autokey_admin_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_autokey_admin_client_client_options_from_dict(): - with mock.patch('google.cloud.kms_v1.services.autokey_admin.transports.AutokeyAdminGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = AutokeyAdminClient( - 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", [ - (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport, "grpc", grpc_helpers), - (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_autokey_admin_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudkms.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - scopes=None, - default_host="cloudkms.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - autokey_admin.UpdateAutokeyConfigRequest, - dict, -]) -def test_update_autokey_config(request_type, transport: str = 'grpc'): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey_admin.AutokeyConfig( - name='name_value', - key_project='key_project_value', - state=autokey_admin.AutokeyConfig.State.ACTIVE, - ) - response = client.update_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = autokey_admin.UpdateAutokeyConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey_admin.AutokeyConfig) - assert response.name == 'name_value' - assert response.key_project == 'key_project_value' - assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE - - -def test_update_autokey_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = autokey_admin.UpdateAutokeyConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_autokey_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_autokey_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == autokey_admin.UpdateAutokeyConfigRequest( - ) - -def test_update_autokey_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_autokey_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_autokey_config] = mock_rpc - request = {} - client.update_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_autokey_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_autokey_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_autokey_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_autokey_config] = mock_rpc - - request = {} - await client.update_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_autokey_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_autokey_config_async(transport: str = 'grpc_asyncio', request_type=autokey_admin.UpdateAutokeyConfigRequest): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig( - name='name_value', - key_project='key_project_value', - state=autokey_admin.AutokeyConfig.State.ACTIVE, - )) - response = await client.update_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = autokey_admin.UpdateAutokeyConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey_admin.AutokeyConfig) - assert response.name == 'name_value' - assert response.key_project == 'key_project_value' - assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE - - -@pytest.mark.asyncio -async def test_update_autokey_config_async_from_dict(): - await test_update_autokey_config_async(request_type=dict) - -def test_update_autokey_config_field_headers(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey_admin.UpdateAutokeyConfigRequest() - - request.autokey_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_autokey_config), - '__call__') as call: - call.return_value = autokey_admin.AutokeyConfig() - client.update_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'autokey_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_autokey_config_field_headers_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey_admin.UpdateAutokeyConfigRequest() - - request.autokey_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_autokey_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig()) - await client.update_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'autokey_config.name=name_value', - ) in kw['metadata'] - - -def test_update_autokey_config_flattened(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey_admin.AutokeyConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_autokey_config( - autokey_config=autokey_admin.AutokeyConfig(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].autokey_config - mock_val = autokey_admin.AutokeyConfig(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_autokey_config_flattened_error(): - client = AutokeyAdminClient( - credentials=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_autokey_config( - autokey_admin.UpdateAutokeyConfigRequest(), - autokey_config=autokey_admin.AutokeyConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_autokey_config_flattened_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey_admin.AutokeyConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_autokey_config( - autokey_config=autokey_admin.AutokeyConfig(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].autokey_config - mock_val = autokey_admin.AutokeyConfig(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_autokey_config_flattened_error_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_autokey_config( - autokey_admin.UpdateAutokeyConfigRequest(), - autokey_config=autokey_admin.AutokeyConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - autokey_admin.GetAutokeyConfigRequest, - dict, -]) -def test_get_autokey_config(request_type, transport: str = 'grpc'): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey_admin.AutokeyConfig( - name='name_value', - key_project='key_project_value', - state=autokey_admin.AutokeyConfig.State.ACTIVE, - ) - response = client.get_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = autokey_admin.GetAutokeyConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey_admin.AutokeyConfig) - assert response.name == 'name_value' - assert response.key_project == 'key_project_value' - assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE - - -def test_get_autokey_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = autokey_admin.GetAutokeyConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_autokey_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_autokey_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == autokey_admin.GetAutokeyConfigRequest( - name='name_value', - ) - -def test_get_autokey_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_autokey_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_autokey_config] = mock_rpc - request = {} - client.get_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_autokey_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_autokey_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_autokey_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_autokey_config] = mock_rpc - - request = {} - await client.get_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_autokey_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_autokey_config_async(transport: str = 'grpc_asyncio', request_type=autokey_admin.GetAutokeyConfigRequest): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig( - name='name_value', - key_project='key_project_value', - state=autokey_admin.AutokeyConfig.State.ACTIVE, - )) - response = await client.get_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = autokey_admin.GetAutokeyConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey_admin.AutokeyConfig) - assert response.name == 'name_value' - assert response.key_project == 'key_project_value' - assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE - - -@pytest.mark.asyncio -async def test_get_autokey_config_async_from_dict(): - await test_get_autokey_config_async(request_type=dict) - -def test_get_autokey_config_field_headers(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey_admin.GetAutokeyConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_autokey_config), - '__call__') as call: - call.return_value = autokey_admin.AutokeyConfig() - client.get_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_autokey_config_field_headers_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey_admin.GetAutokeyConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_autokey_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig()) - await client.get_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_autokey_config_flattened(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey_admin.AutokeyConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_autokey_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_autokey_config_flattened_error(): - client = AutokeyAdminClient( - credentials=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_autokey_config( - autokey_admin.GetAutokeyConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_autokey_config_flattened_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey_admin.AutokeyConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_autokey_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_autokey_config_flattened_error_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_autokey_config( - autokey_admin.GetAutokeyConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - autokey_admin.ShowEffectiveAutokeyConfigRequest, - dict, -]) -def test_show_effective_autokey_config(request_type, transport: str = 'grpc'): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.show_effective_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse( - key_project='key_project_value', - ) - response = client.show_effective_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = autokey_admin.ShowEffectiveAutokeyConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey_admin.ShowEffectiveAutokeyConfigResponse) - assert response.key_project == 'key_project_value' - - -def test_show_effective_autokey_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = autokey_admin.ShowEffectiveAutokeyConfigRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.show_effective_autokey_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.show_effective_autokey_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == autokey_admin.ShowEffectiveAutokeyConfigRequest( - parent='parent_value', - ) - -def test_show_effective_autokey_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.show_effective_autokey_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.show_effective_autokey_config] = mock_rpc - request = {} - client.show_effective_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.show_effective_autokey_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_show_effective_autokey_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.show_effective_autokey_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.show_effective_autokey_config] = mock_rpc - - request = {} - await client.show_effective_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.show_effective_autokey_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_show_effective_autokey_config_async(transport: str = 'grpc_asyncio', request_type=autokey_admin.ShowEffectiveAutokeyConfigRequest): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.show_effective_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.ShowEffectiveAutokeyConfigResponse( - key_project='key_project_value', - )) - response = await client.show_effective_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = autokey_admin.ShowEffectiveAutokeyConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey_admin.ShowEffectiveAutokeyConfigResponse) - assert response.key_project == 'key_project_value' - - -@pytest.mark.asyncio -async def test_show_effective_autokey_config_async_from_dict(): - await test_show_effective_autokey_config_async(request_type=dict) - -def test_show_effective_autokey_config_field_headers(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey_admin.ShowEffectiveAutokeyConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.show_effective_autokey_config), - '__call__') as call: - call.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() - client.show_effective_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_show_effective_autokey_config_field_headers_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = autokey_admin.ShowEffectiveAutokeyConfigRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.show_effective_autokey_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.ShowEffectiveAutokeyConfigResponse()) - await client.show_effective_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_show_effective_autokey_config_flattened(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.show_effective_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.show_effective_autokey_config( - 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_show_effective_autokey_config_flattened_error(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.show_effective_autokey_config( - autokey_admin.ShowEffectiveAutokeyConfigRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_show_effective_autokey_config_flattened_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.show_effective_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.ShowEffectiveAutokeyConfigResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.show_effective_autokey_config( - 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_show_effective_autokey_config_flattened_error_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.show_effective_autokey_config( - autokey_admin.ShowEffectiveAutokeyConfigRequest(), - parent='parent_value', - ) - - -def test_update_autokey_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_autokey_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_autokey_config] = mock_rpc - - request = {} - client.update_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_autokey_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_autokey_config_rest_required_fields(request_type=autokey_admin.UpdateAutokeyConfigRequest): - transport_class = transports.AutokeyAdminRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_autokey_config._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_autokey_config._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 = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = autokey_admin.AutokeyConfig() - # 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 - - # Convert return value to protobuf type - return_value = autokey_admin.AutokeyConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_autokey_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_autokey_config_rest_unset_required_fields(): - transport = transports.AutokeyAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_autokey_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("autokeyConfig", "updateMask", ))) - - -def test_update_autokey_config_rest_flattened(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = autokey_admin.AutokeyConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'autokey_config': {'name': 'folders/sample1/autokeyConfig'}} - - # get truthy value for each flattened field - mock_args = dict( - autokey_config=autokey_admin.AutokeyConfig(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 - # Convert return value to protobuf type - return_value = autokey_admin.AutokeyConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_autokey_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{autokey_config.name=folders/*/autokeyConfig}" % client.transport._host, args[1]) - - -def test_update_autokey_config_rest_flattened_error(transport: str = 'rest'): - client = AutokeyAdminClient( - credentials=ga_credentials.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_autokey_config( - autokey_admin.UpdateAutokeyConfigRequest(), - autokey_config=autokey_admin.AutokeyConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_autokey_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_autokey_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_autokey_config] = mock_rpc - - request = {} - client.get_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_autokey_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_autokey_config_rest_required_fields(request_type=autokey_admin.GetAutokeyConfigRequest): - transport_class = transports.AutokeyAdminRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_autokey_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_autokey_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = autokey_admin.AutokeyConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = autokey_admin.AutokeyConfig.pb(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_autokey_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_autokey_config_rest_unset_required_fields(): - transport = transports.AutokeyAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_autokey_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_autokey_config_rest_flattened(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = autokey_admin.AutokeyConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'folders/sample1/autokeyConfig'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = autokey_admin.AutokeyConfig.pb(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_autokey_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=folders/*/autokeyConfig}" % client.transport._host, args[1]) - - -def test_get_autokey_config_rest_flattened_error(transport: str = 'rest'): - client = AutokeyAdminClient( - credentials=ga_credentials.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_autokey_config( - autokey_admin.GetAutokeyConfigRequest(), - name='name_value', - ) - - -def test_show_effective_autokey_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.show_effective_autokey_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.show_effective_autokey_config] = mock_rpc - - request = {} - client.show_effective_autokey_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.show_effective_autokey_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_show_effective_autokey_config_rest_required_fields(request_type=autokey_admin.ShowEffectiveAutokeyConfigRequest): - transport_class = transports.AutokeyAdminRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).show_effective_autokey_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).show_effective_autokey_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse.pb(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.show_effective_autokey_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_show_effective_autokey_config_rest_unset_required_fields(): - transport = transports.AutokeyAdminRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.show_effective_autokey_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", ))) - - -def test_show_effective_autokey_config_rest_flattened(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse.pb(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.show_effective_autokey_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*}:showEffectiveAutokeyConfig" % client.transport._host, args[1]) - - -def test_show_effective_autokey_config_rest_flattened_error(transport: str = 'rest'): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.show_effective_autokey_config( - autokey_admin.ShowEffectiveAutokeyConfigRequest(), - parent='parent_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AutokeyAdminGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AutokeyAdminGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutokeyAdminClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.AutokeyAdminGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AutokeyAdminClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = AutokeyAdminClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AutokeyAdminGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AutokeyAdminClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AutokeyAdminGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = AutokeyAdminClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AutokeyAdminGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AutokeyAdminGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.AutokeyAdminGrpcTransport, - transports.AutokeyAdminGrpcAsyncIOTransport, - transports.AutokeyAdminRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = AutokeyAdminClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_autokey_config_empty_call_grpc(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_autokey_config), - '__call__') as call: - call.return_value = autokey_admin.AutokeyConfig() - client.update_autokey_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey_admin.UpdateAutokeyConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_autokey_config_empty_call_grpc(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_autokey_config), - '__call__') as call: - call.return_value = autokey_admin.AutokeyConfig() - client.get_autokey_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey_admin.GetAutokeyConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_show_effective_autokey_config_empty_call_grpc(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.show_effective_autokey_config), - '__call__') as call: - call.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() - client.show_effective_autokey_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey_admin.ShowEffectiveAutokeyConfigRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = AutokeyAdminAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_autokey_config_empty_call_grpc_asyncio(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig( - name='name_value', - key_project='key_project_value', - state=autokey_admin.AutokeyConfig.State.ACTIVE, - )) - await client.update_autokey_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey_admin.UpdateAutokeyConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_autokey_config_empty_call_grpc_asyncio(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.AutokeyConfig( - name='name_value', - key_project='key_project_value', - state=autokey_admin.AutokeyConfig.State.ACTIVE, - )) - await client.get_autokey_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey_admin.GetAutokeyConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_show_effective_autokey_config_empty_call_grpc_asyncio(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.show_effective_autokey_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(autokey_admin.ShowEffectiveAutokeyConfigResponse( - key_project='key_project_value', - )) - await client.show_effective_autokey_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey_admin.ShowEffectiveAutokeyConfigRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = AutokeyAdminClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_update_autokey_config_rest_bad_request(request_type=autokey_admin.UpdateAutokeyConfigRequest): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'autokey_config': {'name': 'folders/sample1/autokeyConfig'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_autokey_config(request) - - -@pytest.mark.parametrize("request_type", [ - autokey_admin.UpdateAutokeyConfigRequest, - dict, -]) -def test_update_autokey_config_rest_call_success(request_type): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'autokey_config': {'name': 'folders/sample1/autokeyConfig'}} - request_init["autokey_config"] = {'name': 'folders/sample1/autokeyConfig', 'key_project': 'key_project_value', 'state': 1} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = autokey_admin.UpdateAutokeyConfigRequest.meta.fields["autokey_config"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["autokey_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["autokey_config"][field])): - del request_init["autokey_config"][field][i][subfield] - else: - del request_init["autokey_config"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = autokey_admin.AutokeyConfig( - name='name_value', - key_project='key_project_value', - state=autokey_admin.AutokeyConfig.State.ACTIVE, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = autokey_admin.AutokeyConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_autokey_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey_admin.AutokeyConfig) - assert response.name == 'name_value' - assert response.key_project == 'key_project_value' - assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_autokey_config_rest_interceptors(null_interceptor): - transport = transports.AutokeyAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutokeyAdminRestInterceptor(), - ) - client = AutokeyAdminClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AutokeyAdminRestInterceptor, "post_update_autokey_config") as post, \ - mock.patch.object(transports.AutokeyAdminRestInterceptor, "pre_update_autokey_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = autokey_admin.UpdateAutokeyConfigRequest.pb(autokey_admin.UpdateAutokeyConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = autokey_admin.AutokeyConfig.to_json(autokey_admin.AutokeyConfig()) - req.return_value.content = return_value - - request = autokey_admin.UpdateAutokeyConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = autokey_admin.AutokeyConfig() - - client.update_autokey_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_autokey_config_rest_bad_request(request_type=autokey_admin.GetAutokeyConfigRequest): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'folders/sample1/autokeyConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_autokey_config(request) - - -@pytest.mark.parametrize("request_type", [ - autokey_admin.GetAutokeyConfigRequest, - dict, -]) -def test_get_autokey_config_rest_call_success(request_type): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'folders/sample1/autokeyConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = autokey_admin.AutokeyConfig( - name='name_value', - key_project='key_project_value', - state=autokey_admin.AutokeyConfig.State.ACTIVE, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = autokey_admin.AutokeyConfig.pb(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_autokey_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey_admin.AutokeyConfig) - assert response.name == 'name_value' - assert response.key_project == 'key_project_value' - assert response.state == autokey_admin.AutokeyConfig.State.ACTIVE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_autokey_config_rest_interceptors(null_interceptor): - transport = transports.AutokeyAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutokeyAdminRestInterceptor(), - ) - client = AutokeyAdminClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AutokeyAdminRestInterceptor, "post_get_autokey_config") as post, \ - mock.patch.object(transports.AutokeyAdminRestInterceptor, "pre_get_autokey_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = autokey_admin.GetAutokeyConfigRequest.pb(autokey_admin.GetAutokeyConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = autokey_admin.AutokeyConfig.to_json(autokey_admin.AutokeyConfig()) - req.return_value.content = return_value - - request = autokey_admin.GetAutokeyConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = autokey_admin.AutokeyConfig() - - client.get_autokey_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_show_effective_autokey_config_rest_bad_request(request_type=autokey_admin.ShowEffectiveAutokeyConfigRequest): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.show_effective_autokey_config(request) - - -@pytest.mark.parametrize("request_type", [ - autokey_admin.ShowEffectiveAutokeyConfigRequest, - dict, -]) -def test_show_effective_autokey_config_rest_call_success(request_type): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse( - key_project='key_project_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse.pb(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.show_effective_autokey_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, autokey_admin.ShowEffectiveAutokeyConfigResponse) - assert response.key_project == 'key_project_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_show_effective_autokey_config_rest_interceptors(null_interceptor): - transport = transports.AutokeyAdminRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.AutokeyAdminRestInterceptor(), - ) - client = AutokeyAdminClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.AutokeyAdminRestInterceptor, "post_show_effective_autokey_config") as post, \ - mock.patch.object(transports.AutokeyAdminRestInterceptor, "pre_show_effective_autokey_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = autokey_admin.ShowEffectiveAutokeyConfigRequest.pb(autokey_admin.ShowEffectiveAutokeyConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse.to_json(autokey_admin.ShowEffectiveAutokeyConfigResponse()) - req.return_value.content = return_value - - request = autokey_admin.ShowEffectiveAutokeyConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = autokey_admin.ShowEffectiveAutokeyConfigResponse() - - client.show_effective_autokey_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_initialize_client_w_rest(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_autokey_config_empty_call_rest(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_autokey_config), - '__call__') as call: - client.update_autokey_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey_admin.UpdateAutokeyConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_autokey_config_empty_call_rest(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_autokey_config), - '__call__') as call: - client.get_autokey_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey_admin.GetAutokeyConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_show_effective_autokey_config_empty_call_rest(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.show_effective_autokey_config), - '__call__') as call: - client.show_effective_autokey_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autokey_admin.ShowEffectiveAutokeyConfigRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.AutokeyAdminGrpcTransport, - ) - -def test_autokey_admin_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.AutokeyAdminTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_autokey_admin_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.kms_v1.services.autokey_admin.transports.AutokeyAdminTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.AutokeyAdminTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'update_autokey_config', - 'get_autokey_config', - 'show_effective_autokey_config', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - ) - 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_autokey_admin_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.kms_v1.services.autokey_admin.transports.AutokeyAdminTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AutokeyAdminTransport( - 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', - 'https://www.googleapis.com/auth/cloudkms', -), - quota_project_id="octopus", - ) - - -def test_autokey_admin_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.kms_v1.services.autokey_admin.transports.AutokeyAdminTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.AutokeyAdminTransport() - adc.assert_called_once() - - -def test_autokey_admin_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) - AutokeyAdminClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AutokeyAdminGrpcTransport, - transports.AutokeyAdminGrpcAsyncIOTransport, - ], -) -def test_autokey_admin_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', 'https://www.googleapis.com/auth/cloudkms',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.AutokeyAdminGrpcTransport, - transports.AutokeyAdminGrpcAsyncIOTransport, - transports.AutokeyAdminRestTransport, - ], -) -def test_autokey_admin_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.AutokeyAdminGrpcTransport, grpc_helpers), - (transports.AutokeyAdminGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_autokey_admin_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( - "cloudkms.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - scopes=["1", "2"], - default_host="cloudkms.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.AutokeyAdminGrpcTransport, transports.AutokeyAdminGrpcAsyncIOTransport]) -def test_autokey_admin_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_autokey_admin_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.AutokeyAdminRestTransport ( - 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_autokey_admin_host_no_port(transport_name): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudkms.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_autokey_admin_host_with_port(transport_name): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudkms.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudkms.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_autokey_admin_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = AutokeyAdminClient( - credentials=creds1, - transport=transport_name, - ) - client2 = AutokeyAdminClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.update_autokey_config._session - session2 = client2.transport.update_autokey_config._session - assert session1 != session2 - session1 = client1.transport.get_autokey_config._session - session2 = client2.transport.get_autokey_config._session - assert session1 != session2 - session1 = client1.transport.show_effective_autokey_config._session - session2 = client2.transport.show_effective_autokey_config._session - assert session1 != session2 -def test_autokey_admin_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AutokeyAdminGrpcTransport( - 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_autokey_admin_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.AutokeyAdminGrpcAsyncIOTransport( - 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.AutokeyAdminGrpcTransport, transports.AutokeyAdminGrpcAsyncIOTransport]) -def test_autokey_admin_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.AutokeyAdminGrpcTransport, transports.AutokeyAdminGrpcAsyncIOTransport]) -def test_autokey_admin_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_autokey_config_path(): - folder = "squid" - expected = "folders/{folder}/autokeyConfig".format(folder=folder, ) - actual = AutokeyAdminClient.autokey_config_path(folder) - assert expected == actual - - -def test_parse_autokey_config_path(): - expected = { - "folder": "clam", - } - path = AutokeyAdminClient.autokey_config_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyAdminClient.parse_autokey_config_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = AutokeyAdminClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = AutokeyAdminClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyAdminClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format(folder=folder, ) - actual = AutokeyAdminClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = AutokeyAdminClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyAdminClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format(organization=organization, ) - actual = AutokeyAdminClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = AutokeyAdminClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyAdminClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format(project=project, ) - actual = AutokeyAdminClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = AutokeyAdminClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyAdminClient.parse_common_project_path(path) - assert expected == actual - -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format(project=project, location=location, ) - actual = AutokeyAdminClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = AutokeyAdminClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AutokeyAdminClient.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.AutokeyAdminTransport, '_prep_wrapped_messages') as prep: - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.AutokeyAdminTransport, '_prep_wrapped_messages') as prep: - transport_class = AutokeyAdminClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_get_operation(transport: str = "grpc"): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = AutokeyAdminClient( - 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 = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc_asyncio"): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -def test_get_iam_policy(transport: str = "grpc"): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = "grpc"): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = AutokeyAdminAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = AutokeyAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = AutokeyAdminClient( - 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", [ - (AutokeyAdminClient, transports.AutokeyAdminGrpcTransport), - (AutokeyAdminAsyncClient, transports.AutokeyAdminGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_ekm_service.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_ekm_service.py deleted file mode 100644 index cae1c5765064..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_ekm_service.py +++ /dev/null @@ -1,7787 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.kms_v1.services.ekm_service import EkmServiceAsyncClient -from google.cloud.kms_v1.services.ekm_service import EkmServiceClient -from google.cloud.kms_v1.services.ekm_service import pagers -from google.cloud.kms_v1.services.ekm_service import transports -from google.cloud.kms_v1.types import ekm_service -from google.cloud.location import locations_pb2 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -import google.auth - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert EkmServiceClient._get_default_mtls_endpoint(None) is None - assert EkmServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert EkmServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert EkmServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert EkmServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert EkmServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert EkmServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert EkmServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert EkmServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - EkmServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert EkmServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert EkmServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert EkmServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - EkmServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert EkmServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert EkmServiceClient._get_client_cert_source(None, False) is None - assert EkmServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert EkmServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert EkmServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert EkmServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(EkmServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceClient)) -@mock.patch.object(EkmServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = EkmServiceClient._DEFAULT_UNIVERSE - default_endpoint = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert EkmServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert EkmServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == EkmServiceClient.DEFAULT_MTLS_ENDPOINT - assert EkmServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert EkmServiceClient._get_api_endpoint(None, None, default_universe, "always") == EkmServiceClient.DEFAULT_MTLS_ENDPOINT - assert EkmServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == EkmServiceClient.DEFAULT_MTLS_ENDPOINT - assert EkmServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert EkmServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - EkmServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert EkmServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert EkmServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert EkmServiceClient._get_universe_domain(None, None) == EkmServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - EkmServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EkmServiceClient, "grpc"), - (EkmServiceAsyncClient, "grpc_asyncio"), - (EkmServiceClient, "rest"), -]) -def test_ekm_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudkms.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.EkmServiceGrpcTransport, "grpc"), - (transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.EkmServiceRestTransport, "rest"), -]) -def test_ekm_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (EkmServiceClient, "grpc"), - (EkmServiceAsyncClient, "grpc_asyncio"), - (EkmServiceClient, "rest"), -]) -def test_ekm_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudkms.googleapis.com' - ) - - -def test_ekm_service_client_get_transport_class(): - transport = EkmServiceClient.get_transport_class() - available_transports = [ - transports.EkmServiceGrpcTransport, - transports.EkmServiceRestTransport, - ] - assert transport in available_transports - - transport = EkmServiceClient.get_transport_class("grpc") - assert transport == transports.EkmServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (EkmServiceClient, transports.EkmServiceRestTransport, "rest"), -]) -@mock.patch.object(EkmServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceClient)) -@mock.patch.object(EkmServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceAsyncClient)) -def test_ekm_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(EkmServiceClient, '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(EkmServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "true"), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", "false"), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (EkmServiceClient, transports.EkmServiceRestTransport, "rest", "true"), - (EkmServiceClient, transports.EkmServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(EkmServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceClient)) -@mock.patch.object(EkmServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_ekm_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - EkmServiceClient, EkmServiceAsyncClient -]) -@mock.patch.object(EkmServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceClient)) -@mock.patch.object(EkmServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(EkmServiceAsyncClient)) -def test_ekm_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - EkmServiceClient, EkmServiceAsyncClient -]) -@mock.patch.object(EkmServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceClient)) -@mock.patch.object(EkmServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(EkmServiceAsyncClient)) -def test_ekm_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = EkmServiceClient._DEFAULT_UNIVERSE - default_endpoint = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = EkmServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc"), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (EkmServiceClient, transports.EkmServiceRestTransport, "rest"), -]) -def test_ekm_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (EkmServiceClient, transports.EkmServiceRestTransport, "rest", None), -]) -def test_ekm_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_ekm_service_client_client_options_from_dict(): - with mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = EkmServiceClient( - 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", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport, "grpc", grpc_helpers), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_ekm_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudkms.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - scopes=None, - default_host="cloudkms.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.ListEkmConnectionsRequest, - dict, -]) -def test_list_ekm_connections(request_type, transport: str = 'grpc'): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_ekm_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.ListEkmConnectionsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_ekm_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = ekm_service.ListEkmConnectionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEkmConnectionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_ekm_connections_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = ekm_service.ListEkmConnectionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_ekm_connections(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == ekm_service.ListEkmConnectionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_ekm_connections_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_ekm_connections in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_ekm_connections] = mock_rpc - request = {} - client.list_ekm_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_ekm_connections(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_ekm_connections_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_ekm_connections in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_ekm_connections] = mock_rpc - - request = {} - await client.list_ekm_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_ekm_connections(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_ekm_connections_async(transport: str = 'grpc_asyncio', request_type=ekm_service.ListEkmConnectionsRequest): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_ekm_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = ekm_service.ListEkmConnectionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEkmConnectionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_ekm_connections_async_from_dict(): - await test_list_ekm_connections_async(request_type=dict) - -def test_list_ekm_connections_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.ListEkmConnectionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: - call.return_value = ekm_service.ListEkmConnectionsResponse() - client.list_ekm_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_ekm_connections_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.ListEkmConnectionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse()) - await client.list_ekm_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_ekm_connections_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.ListEkmConnectionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_ekm_connections( - 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_ekm_connections_flattened_error(): - client = EkmServiceClient( - credentials=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_ekm_connections( - ekm_service.ListEkmConnectionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_ekm_connections_flattened_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.ListEkmConnectionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_ekm_connections( - 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_ekm_connections_flattened_error_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_ekm_connections( - ekm_service.ListEkmConnectionsRequest(), - parent='parent_value', - ) - - -def test_list_ekm_connections_pager(transport_name: str = "grpc"): - client = EkmServiceClient( - 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_ekm_connections), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ], - next_page_token='abc', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[], - next_page_token='def', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ], - next_page_token='ghi', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_ekm_connections(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, ekm_service.EkmConnection) - for i in results) -def test_list_ekm_connections_pages(transport_name: str = "grpc"): - client = EkmServiceClient( - 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_ekm_connections), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ], - next_page_token='abc', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[], - next_page_token='def', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ], - next_page_token='ghi', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ], - ), - RuntimeError, - ) - pages = list(client.list_ekm_connections(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_ekm_connections_async_pager(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ], - next_page_token='abc', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[], - next_page_token='def', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ], - next_page_token='ghi', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_ekm_connections(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, ekm_service.EkmConnection) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_ekm_connections_async_pages(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ], - next_page_token='abc', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[], - next_page_token='def', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ], - next_page_token='ghi', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_ekm_connections(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - ekm_service.GetEkmConnectionRequest, - dict, -]) -def test_get_ekm_connection(request_type, transport: str = 'grpc'): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - ) - response = client.get_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = ekm_service.GetEkmConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL - assert response.crypto_space_path == 'crypto_space_path_value' - - -def test_get_ekm_connection_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = ekm_service.GetEkmConnectionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_ekm_connection(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == ekm_service.GetEkmConnectionRequest( - name='name_value', - ) - -def test_get_ekm_connection_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_ekm_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_ekm_connection] = mock_rpc - request = {} - client.get_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_ekm_connection(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_ekm_connection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_ekm_connection in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_ekm_connection] = mock_rpc - - request = {} - await client.get_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_ekm_connection(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.GetEkmConnectionRequest): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - )) - response = await client.get_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = ekm_service.GetEkmConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL - assert response.crypto_space_path == 'crypto_space_path_value' - - -@pytest.mark.asyncio -async def test_get_ekm_connection_async_from_dict(): - await test_get_ekm_connection_async(request_type=dict) - -def test_get_ekm_connection_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.GetEkmConnectionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: - call.return_value = ekm_service.EkmConnection() - client.get_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_ekm_connection_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.GetEkmConnectionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) - await client.get_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_ekm_connection_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConnection() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_ekm_connection( - 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_ekm_connection_flattened_error(): - client = EkmServiceClient( - credentials=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_ekm_connection( - ekm_service.GetEkmConnectionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_ekm_connection_flattened_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConnection() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_ekm_connection( - 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_ekm_connection_flattened_error_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_ekm_connection( - ekm_service.GetEkmConnectionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.CreateEkmConnectionRequest, - dict, -]) -def test_create_ekm_connection(request_type, transport: str = 'grpc'): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - ) - response = client.create_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = ekm_service.CreateEkmConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL - assert response.crypto_space_path == 'crypto_space_path_value' - - -def test_create_ekm_connection_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = ekm_service.CreateEkmConnectionRequest( - parent='parent_value', - ekm_connection_id='ekm_connection_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_ekm_connection(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == ekm_service.CreateEkmConnectionRequest( - parent='parent_value', - ekm_connection_id='ekm_connection_id_value', - ) - -def test_create_ekm_connection_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_ekm_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_ekm_connection] = mock_rpc - request = {} - client.create_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_ekm_connection(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_ekm_connection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_ekm_connection in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_ekm_connection] = mock_rpc - - request = {} - await client.create_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_ekm_connection(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.CreateEkmConnectionRequest): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - )) - response = await client.create_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = ekm_service.CreateEkmConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL - assert response.crypto_space_path == 'crypto_space_path_value' - - -@pytest.mark.asyncio -async def test_create_ekm_connection_async_from_dict(): - await test_create_ekm_connection_async(request_type=dict) - -def test_create_ekm_connection_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.CreateEkmConnectionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: - call.return_value = ekm_service.EkmConnection() - client.create_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_ekm_connection_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.CreateEkmConnectionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) - await client.create_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_ekm_connection_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConnection() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_ekm_connection( - parent='parent_value', - ekm_connection_id='ekm_connection_id_value', - ekm_connection=ekm_service.EkmConnection(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].ekm_connection_id - mock_val = 'ekm_connection_id_value' - assert arg == mock_val - arg = args[0].ekm_connection - mock_val = ekm_service.EkmConnection(name='name_value') - assert arg == mock_val - - -def test_create_ekm_connection_flattened_error(): - client = EkmServiceClient( - credentials=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_ekm_connection( - ekm_service.CreateEkmConnectionRequest(), - parent='parent_value', - ekm_connection_id='ekm_connection_id_value', - ekm_connection=ekm_service.EkmConnection(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_ekm_connection_flattened_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConnection() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_ekm_connection( - parent='parent_value', - ekm_connection_id='ekm_connection_id_value', - ekm_connection=ekm_service.EkmConnection(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].ekm_connection_id - mock_val = 'ekm_connection_id_value' - assert arg == mock_val - arg = args[0].ekm_connection - mock_val = ekm_service.EkmConnection(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_ekm_connection_flattened_error_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_ekm_connection( - ekm_service.CreateEkmConnectionRequest(), - parent='parent_value', - ekm_connection_id='ekm_connection_id_value', - ekm_connection=ekm_service.EkmConnection(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.UpdateEkmConnectionRequest, - dict, -]) -def test_update_ekm_connection(request_type, transport: str = 'grpc'): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - ) - response = client.update_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = ekm_service.UpdateEkmConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL - assert response.crypto_space_path == 'crypto_space_path_value' - - -def test_update_ekm_connection_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = ekm_service.UpdateEkmConnectionRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_ekm_connection(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == ekm_service.UpdateEkmConnectionRequest( - ) - -def test_update_ekm_connection_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_ekm_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_ekm_connection] = mock_rpc - request = {} - client.update_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_ekm_connection(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_ekm_connection_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_ekm_connection in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_ekm_connection] = mock_rpc - - request = {} - await client.update_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_ekm_connection(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_ekm_connection_async(transport: str = 'grpc_asyncio', request_type=ekm_service.UpdateEkmConnectionRequest): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - )) - response = await client.update_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = ekm_service.UpdateEkmConnectionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL - assert response.crypto_space_path == 'crypto_space_path_value' - - -@pytest.mark.asyncio -async def test_update_ekm_connection_async_from_dict(): - await test_update_ekm_connection_async(request_type=dict) - -def test_update_ekm_connection_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.UpdateEkmConnectionRequest() - - request.ekm_connection.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: - call.return_value = ekm_service.EkmConnection() - client.update_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'ekm_connection.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_ekm_connection_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.UpdateEkmConnectionRequest() - - request.ekm_connection.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) - await client.update_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'ekm_connection.name=name_value', - ) in kw['metadata'] - - -def test_update_ekm_connection_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConnection() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_ekm_connection( - ekm_connection=ekm_service.EkmConnection(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].ekm_connection - mock_val = ekm_service.EkmConnection(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_ekm_connection_flattened_error(): - client = EkmServiceClient( - credentials=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_ekm_connection( - ekm_service.UpdateEkmConnectionRequest(), - ekm_connection=ekm_service.EkmConnection(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_ekm_connection_flattened_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConnection() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_ekm_connection( - ekm_connection=ekm_service.EkmConnection(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].ekm_connection - mock_val = ekm_service.EkmConnection(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_ekm_connection_flattened_error_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_ekm_connection( - ekm_service.UpdateEkmConnectionRequest(), - ekm_connection=ekm_service.EkmConnection(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.GetEkmConfigRequest, - dict, -]) -def test_get_ekm_config(request_type, transport: str = 'grpc'): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_ekm_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConfig( - name='name_value', - default_ekm_connection='default_ekm_connection_value', - ) - response = client.get_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = ekm_service.GetEkmConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConfig) - assert response.name == 'name_value' - assert response.default_ekm_connection == 'default_ekm_connection_value' - - -def test_get_ekm_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = ekm_service.GetEkmConfigRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_ekm_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == ekm_service.GetEkmConfigRequest( - name='name_value', - ) - -def test_get_ekm_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_ekm_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_ekm_config] = mock_rpc - request = {} - client.get_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_ekm_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_ekm_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_ekm_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_ekm_config] = mock_rpc - - request = {} - await client.get_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_ekm_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_ekm_config_async(transport: str = 'grpc_asyncio', request_type=ekm_service.GetEkmConfigRequest): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig( - name='name_value', - default_ekm_connection='default_ekm_connection_value', - )) - response = await client.get_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = ekm_service.GetEkmConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConfig) - assert response.name == 'name_value' - assert response.default_ekm_connection == 'default_ekm_connection_value' - - -@pytest.mark.asyncio -async def test_get_ekm_config_async_from_dict(): - await test_get_ekm_config_async(request_type=dict) - -def test_get_ekm_config_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.GetEkmConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_config), - '__call__') as call: - call.return_value = ekm_service.EkmConfig() - client.get_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_get_ekm_config_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.GetEkmConfigRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig()) - await client.get_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -def test_get_ekm_config_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_ekm_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - - -def test_get_ekm_config_flattened_error(): - client = EkmServiceClient( - credentials=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_ekm_config( - ekm_service.GetEkmConfigRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_ekm_config_flattened_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_ekm_config( - name='name_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_get_ekm_config_flattened_error_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_ekm_config( - ekm_service.GetEkmConfigRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.UpdateEkmConfigRequest, - dict, -]) -def test_update_ekm_config(request_type, transport: str = 'grpc'): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_ekm_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConfig( - name='name_value', - default_ekm_connection='default_ekm_connection_value', - ) - response = client.update_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = ekm_service.UpdateEkmConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConfig) - assert response.name == 'name_value' - assert response.default_ekm_connection == 'default_ekm_connection_value' - - -def test_update_ekm_config_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = ekm_service.UpdateEkmConfigRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_config), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_ekm_config(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == ekm_service.UpdateEkmConfigRequest( - ) - -def test_update_ekm_config_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_ekm_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_ekm_config] = mock_rpc - request = {} - client.update_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_ekm_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_ekm_config_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_ekm_config in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_ekm_config] = mock_rpc - - request = {} - await client.update_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_ekm_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_ekm_config_async(transport: str = 'grpc_asyncio', request_type=ekm_service.UpdateEkmConfigRequest): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig( - name='name_value', - default_ekm_connection='default_ekm_connection_value', - )) - response = await client.update_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = ekm_service.UpdateEkmConfigRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConfig) - assert response.name == 'name_value' - assert response.default_ekm_connection == 'default_ekm_connection_value' - - -@pytest.mark.asyncio -async def test_update_ekm_config_async_from_dict(): - await test_update_ekm_config_async(request_type=dict) - -def test_update_ekm_config_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.UpdateEkmConfigRequest() - - request.ekm_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_config), - '__call__') as call: - call.return_value = ekm_service.EkmConfig() - client.update_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'ekm_config.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_ekm_config_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.UpdateEkmConfigRequest() - - request.ekm_config.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_config), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig()) - await client.update_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'ekm_config.name=name_value', - ) in kw['metadata'] - - -def test_update_ekm_config_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConfig() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_ekm_config( - ekm_config=ekm_service.EkmConfig(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].ekm_config - mock_val = ekm_service.EkmConfig(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_ekm_config_flattened_error(): - client = EkmServiceClient( - credentials=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_ekm_config( - ekm_service.UpdateEkmConfigRequest(), - ekm_config=ekm_service.EkmConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_ekm_config_flattened_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.EkmConfig() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_ekm_config( - ekm_config=ekm_service.EkmConfig(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].ekm_config - mock_val = ekm_service.EkmConfig(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_ekm_config_flattened_error_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_ekm_config( - ekm_service.UpdateEkmConfigRequest(), - ekm_config=ekm_service.EkmConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.VerifyConnectivityRequest, - dict, -]) -def test_verify_connectivity(request_type, transport: str = 'grpc'): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.verify_connectivity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.VerifyConnectivityResponse( - ) - response = client.verify_connectivity(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = ekm_service.VerifyConnectivityRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.VerifyConnectivityResponse) - - -def test_verify_connectivity_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = ekm_service.VerifyConnectivityRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.verify_connectivity), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.verify_connectivity(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == ekm_service.VerifyConnectivityRequest( - name='name_value', - ) - -def test_verify_connectivity_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.verify_connectivity in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.verify_connectivity] = mock_rpc - request = {} - client.verify_connectivity(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.verify_connectivity(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_verify_connectivity_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.verify_connectivity in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.verify_connectivity] = mock_rpc - - request = {} - await client.verify_connectivity(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.verify_connectivity(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_verify_connectivity_async(transport: str = 'grpc_asyncio', request_type=ekm_service.VerifyConnectivityRequest): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.verify_connectivity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.VerifyConnectivityResponse( - )) - response = await client.verify_connectivity(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = ekm_service.VerifyConnectivityRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.VerifyConnectivityResponse) - - -@pytest.mark.asyncio -async def test_verify_connectivity_async_from_dict(): - await test_verify_connectivity_async(request_type=dict) - -def test_verify_connectivity_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.VerifyConnectivityRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.verify_connectivity), - '__call__') as call: - call.return_value = ekm_service.VerifyConnectivityResponse() - client.verify_connectivity(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_verify_connectivity_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = ekm_service.VerifyConnectivityRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.verify_connectivity), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.VerifyConnectivityResponse()) - await client.verify_connectivity(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_verify_connectivity_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.verify_connectivity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.VerifyConnectivityResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.verify_connectivity( - 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_verify_connectivity_flattened_error(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.verify_connectivity( - ekm_service.VerifyConnectivityRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_verify_connectivity_flattened_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.verify_connectivity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = ekm_service.VerifyConnectivityResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.VerifyConnectivityResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.verify_connectivity( - 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_verify_connectivity_flattened_error_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.verify_connectivity( - ekm_service.VerifyConnectivityRequest(), - name='name_value', - ) - - -def test_list_ekm_connections_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_ekm_connections in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_ekm_connections] = mock_rpc - - request = {} - client.list_ekm_connections(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_ekm_connections(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_ekm_connections_rest_required_fields(request_type=ekm_service.ListEkmConnectionsRequest): - transport_class = transports.EkmServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_ekm_connections._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_ekm_connections._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = ekm_service.ListEkmConnectionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.ListEkmConnectionsResponse.pb(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_ekm_connections(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_ekm_connections_rest_unset_required_fields(): - transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_ekm_connections._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_ekm_connections_rest_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.ListEkmConnectionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ekm_service.ListEkmConnectionsResponse.pb(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_ekm_connections(**mock_args) - - # Establish that the underlying call 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/*}/ekmConnections" % client.transport._host, args[1]) - - -def test_list_ekm_connections_rest_flattened_error(transport: str = 'rest'): - client = EkmServiceClient( - credentials=ga_credentials.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_ekm_connections( - ekm_service.ListEkmConnectionsRequest(), - parent='parent_value', - ) - - -def test_list_ekm_connections_rest_pager(transport: str = 'rest'): - client = EkmServiceClient( - 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 = ( - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ], - next_page_token='abc', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[], - next_page_token='def', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ], - next_page_token='ghi', - ), - ekm_service.ListEkmConnectionsResponse( - ekm_connections=[ - ekm_service.EkmConnection(), - ekm_service.EkmConnection(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(ekm_service.ListEkmConnectionsResponse.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_ekm_connections(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, ekm_service.EkmConnection) - for i in results) - - pages = list(client.list_ekm_connections(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_ekm_connection_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_ekm_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_ekm_connection] = mock_rpc - - request = {} - client.get_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_ekm_connection(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_ekm_connection_rest_required_fields(request_type=ekm_service.GetEkmConnectionRequest): - transport_class = transports.EkmServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_ekm_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_ekm_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConnection() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.EkmConnection.pb(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_ekm_connection(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_ekm_connection_rest_unset_required_fields(): - transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_ekm_connection._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_ekm_connection_rest_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConnection() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ekm_service.EkmConnection.pb(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_ekm_connection(**mock_args) - - # Establish that the underlying call 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/*/ekmConnections/*}" % client.transport._host, args[1]) - - -def test_get_ekm_connection_rest_flattened_error(transport: str = 'rest'): - client = EkmServiceClient( - credentials=ga_credentials.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_ekm_connection( - ekm_service.GetEkmConnectionRequest(), - name='name_value', - ) - - -def test_create_ekm_connection_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_ekm_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_ekm_connection] = mock_rpc - - request = {} - client.create_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_ekm_connection(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_ekm_connection_rest_required_fields(request_type=ekm_service.CreateEkmConnectionRequest): - transport_class = transports.EkmServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["ekm_connection_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "ekmConnectionId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_ekm_connection._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "ekmConnectionId" in jsonified_request - assert jsonified_request["ekmConnectionId"] == request_init["ekm_connection_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["ekmConnectionId"] = 'ekm_connection_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_ekm_connection._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("ekm_connection_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "ekmConnectionId" in jsonified_request - assert jsonified_request["ekmConnectionId"] == 'ekm_connection_id_value' - - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConnection() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.EkmConnection.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_ekm_connection(request) - - expected_params = [ - ( - "ekmConnectionId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_ekm_connection_rest_unset_required_fields(): - transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_ekm_connection._get_unset_required_fields({}) - assert set(unset_fields) == (set(("ekmConnectionId", )) & set(("parent", "ekmConnectionId", "ekmConnection", ))) - - -def test_create_ekm_connection_rest_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConnection() - - # 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', - ekm_connection_id='ekm_connection_id_value', - ekm_connection=ekm_service.EkmConnection(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ekm_service.EkmConnection.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_ekm_connection(**mock_args) - - # Establish that the underlying call 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/*}/ekmConnections" % client.transport._host, args[1]) - - -def test_create_ekm_connection_rest_flattened_error(transport: str = 'rest'): - client = EkmServiceClient( - credentials=ga_credentials.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_ekm_connection( - ekm_service.CreateEkmConnectionRequest(), - parent='parent_value', - ekm_connection_id='ekm_connection_id_value', - ekm_connection=ekm_service.EkmConnection(name='name_value'), - ) - - -def test_update_ekm_connection_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_ekm_connection in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_ekm_connection] = mock_rpc - - request = {} - client.update_ekm_connection(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_ekm_connection(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_ekm_connection_rest_required_fields(request_type=ekm_service.UpdateEkmConnectionRequest): - transport_class = transports.EkmServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_ekm_connection._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_ekm_connection._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 = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConnection() - # 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 - - # Convert return value to protobuf type - return_value = ekm_service.EkmConnection.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_ekm_connection(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_ekm_connection_rest_unset_required_fields(): - transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_ekm_connection._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("ekmConnection", "updateMask", ))) - - -def test_update_ekm_connection_rest_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConnection() - - # get arguments that satisfy an http rule for this method - sample_request = {'ekm_connection': {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'}} - - # get truthy value for each flattened field - mock_args = dict( - ekm_connection=ekm_service.EkmConnection(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 - # Convert return value to protobuf type - return_value = ekm_service.EkmConnection.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_ekm_connection(**mock_args) - - # Establish that the underlying call 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/{ekm_connection.name=projects/*/locations/*/ekmConnections/*}" % client.transport._host, args[1]) - - -def test_update_ekm_connection_rest_flattened_error(transport: str = 'rest'): - client = EkmServiceClient( - credentials=ga_credentials.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_ekm_connection( - ekm_service.UpdateEkmConnectionRequest(), - ekm_connection=ekm_service.EkmConnection(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_get_ekm_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_ekm_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_ekm_config] = mock_rpc - - request = {} - client.get_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_ekm_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_ekm_config_rest_required_fields(request_type=ekm_service.GetEkmConfigRequest): - transport_class = transports.EkmServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_ekm_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_ekm_config._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConfig() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.EkmConfig.pb(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_ekm_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_ekm_config_rest_unset_required_fields(): - transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_ekm_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_ekm_config_rest_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/ekmConfig'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ekm_service.EkmConfig.pb(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_ekm_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{name=projects/*/locations/*/ekmConfig}" % client.transport._host, args[1]) - - -def test_get_ekm_config_rest_flattened_error(transport: str = 'rest'): - client = EkmServiceClient( - credentials=ga_credentials.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_ekm_config( - ekm_service.GetEkmConfigRequest(), - name='name_value', - ) - - -def test_update_ekm_config_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_ekm_config in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_ekm_config] = mock_rpc - - request = {} - client.update_ekm_config(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_ekm_config(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_ekm_config_rest_required_fields(request_type=ekm_service.UpdateEkmConfigRequest): - transport_class = transports.EkmServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_ekm_config._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_ekm_config._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 = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConfig() - # 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 - - # Convert return value to protobuf type - return_value = ekm_service.EkmConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_ekm_config(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_ekm_config_rest_unset_required_fields(): - transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_ekm_config._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("ekmConfig", "updateMask", ))) - - -def test_update_ekm_config_rest_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConfig() - - # get arguments that satisfy an http rule for this method - sample_request = {'ekm_config': {'name': 'projects/sample1/locations/sample2/ekmConfig'}} - - # get truthy value for each flattened field - mock_args = dict( - ekm_config=ekm_service.EkmConfig(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 - # Convert return value to protobuf type - return_value = ekm_service.EkmConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_ekm_config(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{ekm_config.name=projects/*/locations/*/ekmConfig}" % client.transport._host, args[1]) - - -def test_update_ekm_config_rest_flattened_error(transport: str = 'rest'): - client = EkmServiceClient( - credentials=ga_credentials.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_ekm_config( - ekm_service.UpdateEkmConfigRequest(), - ekm_config=ekm_service.EkmConfig(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_verify_connectivity_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.verify_connectivity in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.verify_connectivity] = mock_rpc - - request = {} - client.verify_connectivity(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.verify_connectivity(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_verify_connectivity_rest_required_fields(request_type=ekm_service.VerifyConnectivityRequest): - transport_class = transports.EkmServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).verify_connectivity._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).verify_connectivity._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = ekm_service.VerifyConnectivityResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.VerifyConnectivityResponse.pb(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.verify_connectivity(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_verify_connectivity_rest_unset_required_fields(): - transport = transports.EkmServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.verify_connectivity._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_verify_connectivity_rest_flattened(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.VerifyConnectivityResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = ekm_service.VerifyConnectivityResponse.pb(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.verify_connectivity(**mock_args) - - # Establish that the underlying call 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/*/ekmConnections/*}:verifyConnectivity" % client.transport._host, args[1]) - - -def test_verify_connectivity_rest_flattened_error(transport: str = 'rest'): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.verify_connectivity( - ekm_service.VerifyConnectivityRequest(), - name='name_value', - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.EkmServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.EkmServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EkmServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.EkmServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EkmServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = EkmServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.EkmServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = EkmServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.EkmServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = EkmServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.EkmServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.EkmServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.EkmServiceGrpcTransport, - transports.EkmServiceGrpcAsyncIOTransport, - transports.EkmServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = EkmServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_ekm_connections_empty_call_grpc(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: - call.return_value = ekm_service.ListEkmConnectionsResponse() - client.list_ekm_connections(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.ListEkmConnectionsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_ekm_connection_empty_call_grpc(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: - call.return_value = ekm_service.EkmConnection() - client.get_ekm_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.GetEkmConnectionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_ekm_connection_empty_call_grpc(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: - call.return_value = ekm_service.EkmConnection() - client.create_ekm_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.CreateEkmConnectionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_ekm_connection_empty_call_grpc(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: - call.return_value = ekm_service.EkmConnection() - client.update_ekm_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.UpdateEkmConnectionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_ekm_config_empty_call_grpc(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_config), - '__call__') as call: - call.return_value = ekm_service.EkmConfig() - client.get_ekm_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.GetEkmConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_ekm_config_empty_call_grpc(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_config), - '__call__') as call: - call.return_value = ekm_service.EkmConfig() - client.update_ekm_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.UpdateEkmConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_verify_connectivity_empty_call_grpc(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.verify_connectivity), - '__call__') as call: - call.return_value = ekm_service.VerifyConnectivityResponse() - client.verify_connectivity(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.VerifyConnectivityRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = EkmServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_ekm_connections_empty_call_grpc_asyncio(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.ListEkmConnectionsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_ekm_connections(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.ListEkmConnectionsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_ekm_connection_empty_call_grpc_asyncio(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - )) - await client.get_ekm_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.GetEkmConnectionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_ekm_connection_empty_call_grpc_asyncio(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - )) - await client.create_ekm_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.CreateEkmConnectionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_ekm_connection_empty_call_grpc_asyncio(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - )) - await client.update_ekm_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.UpdateEkmConnectionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_ekm_config_empty_call_grpc_asyncio(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig( - name='name_value', - default_ekm_connection='default_ekm_connection_value', - )) - await client.get_ekm_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.GetEkmConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_ekm_config_empty_call_grpc_asyncio(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_config), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.EkmConfig( - name='name_value', - default_ekm_connection='default_ekm_connection_value', - )) - await client.update_ekm_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.UpdateEkmConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_verify_connectivity_empty_call_grpc_asyncio(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.verify_connectivity), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(ekm_service.VerifyConnectivityResponse( - )) - await client.verify_connectivity(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.VerifyConnectivityRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = EkmServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_ekm_connections_rest_bad_request(request_type=ekm_service.ListEkmConnectionsRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_ekm_connections(request) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.ListEkmConnectionsRequest, - dict, -]) -def test_list_ekm_connections_rest_call_success(request_type): - client = EkmServiceClient( - 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 = ekm_service.ListEkmConnectionsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.ListEkmConnectionsResponse.pb(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_ekm_connections(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEkmConnectionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_ekm_connections_rest_interceptors(null_interceptor): - transport = transports.EkmServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), - ) - client = EkmServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "post_list_ekm_connections") as post, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "pre_list_ekm_connections") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ekm_service.ListEkmConnectionsRequest.pb(ekm_service.ListEkmConnectionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = ekm_service.ListEkmConnectionsResponse.to_json(ekm_service.ListEkmConnectionsResponse()) - req.return_value.content = return_value - - request = ekm_service.ListEkmConnectionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ekm_service.ListEkmConnectionsResponse() - - client.list_ekm_connections(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_ekm_connection_rest_bad_request(request_type=ekm_service.GetEkmConnectionRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_ekm_connection(request) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.GetEkmConnectionRequest, - dict, -]) -def test_get_ekm_connection_rest_call_success(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.EkmConnection.pb(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_ekm_connection(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL - assert response.crypto_space_path == 'crypto_space_path_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_ekm_connection_rest_interceptors(null_interceptor): - transport = transports.EkmServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), - ) - client = EkmServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "post_get_ekm_connection") as post, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "pre_get_ekm_connection") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ekm_service.GetEkmConnectionRequest.pb(ekm_service.GetEkmConnectionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = ekm_service.EkmConnection.to_json(ekm_service.EkmConnection()) - req.return_value.content = return_value - - request = ekm_service.GetEkmConnectionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ekm_service.EkmConnection() - - client.get_ekm_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_ekm_connection_rest_bad_request(request_type=ekm_service.CreateEkmConnectionRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.create_ekm_connection(request) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.CreateEkmConnectionRequest, - dict, -]) -def test_create_ekm_connection_rest_call_success(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["ekm_connection"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}, 'service_resolvers': [{'service_directory_service': 'service_directory_service_value', 'endpoint_filter': 'endpoint_filter_value', 'hostname': 'hostname_value', 'server_certificates': [{'raw_der': b'raw_der_blob', 'parsed': True, 'issuer': 'issuer_value', 'subject': 'subject_value', 'subject_alternative_dns_names': ['subject_alternative_dns_names_value1', 'subject_alternative_dns_names_value2'], 'not_before_time': {}, 'not_after_time': {}, 'serial_number': 'serial_number_value', 'sha256_fingerprint': 'sha256_fingerprint_value'}]}], 'etag': 'etag_value', 'key_management_mode': 1, 'crypto_space_path': 'crypto_space_path_value'} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = ekm_service.CreateEkmConnectionRequest.meta.fields["ekm_connection"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["ekm_connection"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["ekm_connection"][field])): - del request_init["ekm_connection"][field][i][subfield] - else: - del request_init["ekm_connection"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.EkmConnection.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_ekm_connection(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL - assert response.crypto_space_path == 'crypto_space_path_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_ekm_connection_rest_interceptors(null_interceptor): - transport = transports.EkmServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), - ) - client = EkmServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "post_create_ekm_connection") as post, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "pre_create_ekm_connection") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ekm_service.CreateEkmConnectionRequest.pb(ekm_service.CreateEkmConnectionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = ekm_service.EkmConnection.to_json(ekm_service.EkmConnection()) - req.return_value.content = return_value - - request = ekm_service.CreateEkmConnectionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ekm_service.EkmConnection() - - client.create_ekm_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_ekm_connection_rest_bad_request(request_type=ekm_service.UpdateEkmConnectionRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'ekm_connection': {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_ekm_connection(request) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.UpdateEkmConnectionRequest, - dict, -]) -def test_update_ekm_connection_rest_call_success(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'ekm_connection': {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'}} - request_init["ekm_connection"] = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3', 'create_time': {'seconds': 751, 'nanos': 543}, 'service_resolvers': [{'service_directory_service': 'service_directory_service_value', 'endpoint_filter': 'endpoint_filter_value', 'hostname': 'hostname_value', 'server_certificates': [{'raw_der': b'raw_der_blob', 'parsed': True, 'issuer': 'issuer_value', 'subject': 'subject_value', 'subject_alternative_dns_names': ['subject_alternative_dns_names_value1', 'subject_alternative_dns_names_value2'], 'not_before_time': {}, 'not_after_time': {}, 'serial_number': 'serial_number_value', 'sha256_fingerprint': 'sha256_fingerprint_value'}]}], 'etag': 'etag_value', 'key_management_mode': 1, 'crypto_space_path': 'crypto_space_path_value'} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = ekm_service.UpdateEkmConnectionRequest.meta.fields["ekm_connection"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["ekm_connection"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["ekm_connection"][field])): - del request_init["ekm_connection"][field][i][subfield] - else: - del request_init["ekm_connection"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConnection( - name='name_value', - etag='etag_value', - key_management_mode=ekm_service.EkmConnection.KeyManagementMode.MANUAL, - crypto_space_path='crypto_space_path_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.EkmConnection.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_ekm_connection(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConnection) - assert response.name == 'name_value' - assert response.etag == 'etag_value' - assert response.key_management_mode == ekm_service.EkmConnection.KeyManagementMode.MANUAL - assert response.crypto_space_path == 'crypto_space_path_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_ekm_connection_rest_interceptors(null_interceptor): - transport = transports.EkmServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), - ) - client = EkmServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "post_update_ekm_connection") as post, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "pre_update_ekm_connection") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ekm_service.UpdateEkmConnectionRequest.pb(ekm_service.UpdateEkmConnectionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = ekm_service.EkmConnection.to_json(ekm_service.EkmConnection()) - req.return_value.content = return_value - - request = ekm_service.UpdateEkmConnectionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ekm_service.EkmConnection() - - client.update_ekm_connection(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_ekm_config_rest_bad_request(request_type=ekm_service.GetEkmConfigRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/ekmConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_ekm_config(request) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.GetEkmConfigRequest, - dict, -]) -def test_get_ekm_config_rest_call_success(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/ekmConfig'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConfig( - name='name_value', - default_ekm_connection='default_ekm_connection_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.EkmConfig.pb(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_ekm_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConfig) - assert response.name == 'name_value' - assert response.default_ekm_connection == 'default_ekm_connection_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_ekm_config_rest_interceptors(null_interceptor): - transport = transports.EkmServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), - ) - client = EkmServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "post_get_ekm_config") as post, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "pre_get_ekm_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ekm_service.GetEkmConfigRequest.pb(ekm_service.GetEkmConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = ekm_service.EkmConfig.to_json(ekm_service.EkmConfig()) - req.return_value.content = return_value - - request = ekm_service.GetEkmConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ekm_service.EkmConfig() - - client.get_ekm_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_ekm_config_rest_bad_request(request_type=ekm_service.UpdateEkmConfigRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'ekm_config': {'name': 'projects/sample1/locations/sample2/ekmConfig'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_ekm_config(request) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.UpdateEkmConfigRequest, - dict, -]) -def test_update_ekm_config_rest_call_success(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'ekm_config': {'name': 'projects/sample1/locations/sample2/ekmConfig'}} - request_init["ekm_config"] = {'name': 'projects/sample1/locations/sample2/ekmConfig', 'default_ekm_connection': 'default_ekm_connection_value'} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = ekm_service.UpdateEkmConfigRequest.meta.fields["ekm_config"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["ekm_config"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["ekm_config"][field])): - del request_init["ekm_config"][field][i][subfield] - else: - del request_init["ekm_config"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.EkmConfig( - name='name_value', - default_ekm_connection='default_ekm_connection_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.EkmConfig.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_ekm_config(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.EkmConfig) - assert response.name == 'name_value' - assert response.default_ekm_connection == 'default_ekm_connection_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_ekm_config_rest_interceptors(null_interceptor): - transport = transports.EkmServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), - ) - client = EkmServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "post_update_ekm_config") as post, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "pre_update_ekm_config") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ekm_service.UpdateEkmConfigRequest.pb(ekm_service.UpdateEkmConfigRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = ekm_service.EkmConfig.to_json(ekm_service.EkmConfig()) - req.return_value.content = return_value - - request = ekm_service.UpdateEkmConfigRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ekm_service.EkmConfig() - - client.update_ekm_config(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_verify_connectivity_rest_bad_request(request_type=ekm_service.VerifyConnectivityRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.verify_connectivity(request) - - -@pytest.mark.parametrize("request_type", [ - ekm_service.VerifyConnectivityRequest, - dict, -]) -def test_verify_connectivity_rest_call_success(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/ekmConnections/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = ekm_service.VerifyConnectivityResponse( - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = ekm_service.VerifyConnectivityResponse.pb(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.verify_connectivity(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, ekm_service.VerifyConnectivityResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_verify_connectivity_rest_interceptors(null_interceptor): - transport = transports.EkmServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.EkmServiceRestInterceptor(), - ) - client = EkmServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "post_verify_connectivity") as post, \ - mock.patch.object(transports.EkmServiceRestInterceptor, "pre_verify_connectivity") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = ekm_service.VerifyConnectivityRequest.pb(ekm_service.VerifyConnectivityRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = ekm_service.VerifyConnectivityResponse.to_json(ekm_service.VerifyConnectivityResponse()) - req.return_value.content = return_value - - request = ekm_service.VerifyConnectivityRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = ekm_service.VerifyConnectivityResponse() - - client.verify_connectivity(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_initialize_client_w_rest(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_ekm_connections_empty_call_rest(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_ekm_connections), - '__call__') as call: - client.list_ekm_connections(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.ListEkmConnectionsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_ekm_connection_empty_call_rest(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_connection), - '__call__') as call: - client.get_ekm_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.GetEkmConnectionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_ekm_connection_empty_call_rest(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_ekm_connection), - '__call__') as call: - client.create_ekm_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.CreateEkmConnectionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_ekm_connection_empty_call_rest(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_connection), - '__call__') as call: - client.update_ekm_connection(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.UpdateEkmConnectionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_ekm_config_empty_call_rest(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_ekm_config), - '__call__') as call: - client.get_ekm_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.GetEkmConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_ekm_config_empty_call_rest(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_ekm_config), - '__call__') as call: - client.update_ekm_config(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.UpdateEkmConfigRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_verify_connectivity_empty_call_rest(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.verify_connectivity), - '__call__') as call: - client.verify_connectivity(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ekm_service.VerifyConnectivityRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.EkmServiceGrpcTransport, - ) - -def test_ekm_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.EkmServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_ekm_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.EkmServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_ekm_connections', - 'get_ekm_connection', - 'create_ekm_connection', - 'update_ekm_connection', - 'get_ekm_config', - 'update_ekm_config', - 'verify_connectivity', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - ) - 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_ekm_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EkmServiceTransport( - 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', - 'https://www.googleapis.com/auth/cloudkms', -), - quota_project_id="octopus", - ) - - -def test_ekm_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.kms_v1.services.ekm_service.transports.EkmServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.EkmServiceTransport() - adc.assert_called_once() - - -def test_ekm_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - EkmServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EkmServiceGrpcTransport, - transports.EkmServiceGrpcAsyncIOTransport, - ], -) -def test_ekm_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloudkms',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.EkmServiceGrpcTransport, - transports.EkmServiceGrpcAsyncIOTransport, - transports.EkmServiceRestTransport, - ], -) -def test_ekm_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.EkmServiceGrpcTransport, grpc_helpers), - (transports.EkmServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_ekm_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "cloudkms.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - scopes=["1", "2"], - default_host="cloudkms.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) -def test_ekm_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_ekm_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.EkmServiceRestTransport ( - 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_ekm_service_host_no_port(transport_name): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudkms.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_ekm_service_host_with_port(transport_name): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudkms.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudkms.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_ekm_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = EkmServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = EkmServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_ekm_connections._session - session2 = client2.transport.list_ekm_connections._session - assert session1 != session2 - session1 = client1.transport.get_ekm_connection._session - session2 = client2.transport.get_ekm_connection._session - assert session1 != session2 - session1 = client1.transport.create_ekm_connection._session - session2 = client2.transport.create_ekm_connection._session - assert session1 != session2 - session1 = client1.transport.update_ekm_connection._session - session2 = client2.transport.update_ekm_connection._session - assert session1 != session2 - session1 = client1.transport.get_ekm_config._session - session2 = client2.transport.get_ekm_config._session - assert session1 != session2 - session1 = client1.transport.update_ekm_config._session - session2 = client2.transport.update_ekm_config._session - assert session1 != session2 - session1 = client1.transport.verify_connectivity._session - session2 = client2.transport.verify_connectivity._session - assert session1 != session2 -def test_ekm_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EkmServiceGrpcTransport( - 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_ekm_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.EkmServiceGrpcAsyncIOTransport( - 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.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) -def test_ekm_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.EkmServiceGrpcTransport, transports.EkmServiceGrpcAsyncIOTransport]) -def test_ekm_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_ekm_config_path(): - project = "squid" - location = "clam" - expected = "projects/{project}/locations/{location}/ekmConfig".format(project=project, location=location, ) - actual = EkmServiceClient.ekm_config_path(project, location) - assert expected == actual - - -def test_parse_ekm_config_path(): - expected = { - "project": "whelk", - "location": "octopus", - } - path = EkmServiceClient.ekm_config_path(**expected) - - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_ekm_config_path(path) - assert expected == actual - -def test_ekm_connection_path(): - project = "oyster" - location = "nudibranch" - ekm_connection = "cuttlefish" - expected = "projects/{project}/locations/{location}/ekmConnections/{ekm_connection}".format(project=project, location=location, ekm_connection=ekm_connection, ) - actual = EkmServiceClient.ekm_connection_path(project, location, ekm_connection) - assert expected == actual - - -def test_parse_ekm_connection_path(): - expected = { - "project": "mussel", - "location": "winkle", - "ekm_connection": "nautilus", - } - path = EkmServiceClient.ekm_connection_path(**expected) - - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_ekm_connection_path(path) - assert expected == actual - -def test_service_path(): - project = "scallop" - location = "abalone" - namespace = "squid" - service = "clam" - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(project=project, location=location, namespace=namespace, service=service, ) - actual = EkmServiceClient.service_path(project, location, namespace, service) - assert expected == actual - - -def test_parse_service_path(): - expected = { - "project": "whelk", - "location": "octopus", - "namespace": "oyster", - "service": "nudibranch", - } - path = EkmServiceClient.service_path(**expected) - - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_service_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = EkmServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = EkmServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = EkmServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = EkmServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = EkmServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = EkmServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = EkmServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = EkmServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = EkmServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = EkmServiceClient.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 = EkmServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = EkmServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = EkmServiceClient.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.EkmServiceTransport, '_prep_wrapped_messages') as prep: - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.EkmServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = EkmServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_get_operation(transport: str = "grpc"): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = EkmServiceClient( - 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 = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc_asyncio"): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -def test_get_iam_policy(transport: str = "grpc"): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = "grpc"): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = EkmServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = EkmServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = EkmServiceClient( - 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", [ - (EkmServiceClient, transports.EkmServiceGrpcTransport), - (EkmServiceAsyncClient, transports.EkmServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_key_management_service.py b/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_key_management_service.py deleted file mode 100644 index 6ee519ae5ede..000000000000 --- a/owl-bot-staging/google-cloud-kms/v1/tests/unit/gapic/kms_v1/test_key_management_service.py +++ /dev/null @@ -1,22906 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -import os -# try/except added for compatibility with python < 3.8 -try: - from unittest import mock - from unittest.mock import AsyncMock # pragma: NO COVER -except ImportError: # pragma: NO COVER - import mock - -import grpc -from grpc.experimental import aio -from collections.abc import Iterable, AsyncIterable -from google.protobuf import json_format -import json -import math -import pytest -from google.api_core import api_core_version -from proto.marshal.rules.dates import DurationRule, TimestampRule -from proto.marshal.rules import wrappers -from requests import Response -from requests import Request, PreparedRequest -from requests.sessions import Session -from google.protobuf import json_format - -try: - from google.auth.aio import credentials as ga_credentials_async - HAS_GOOGLE_AUTH_AIO = True -except ImportError: # pragma: NO COVER - HAS_GOOGLE_AUTH_AIO = False - -from google.api_core import client_options -from google.api_core import exceptions as core_exceptions -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import path_template -from google.api_core import retry as retries -from google.auth import credentials as ga_credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.kms_v1.services.key_management_service import KeyManagementServiceAsyncClient -from google.cloud.kms_v1.services.key_management_service import KeyManagementServiceClient -from google.cloud.kms_v1.services.key_management_service import pagers -from google.cloud.kms_v1.services.key_management_service import transports -from google.cloud.kms_v1.types import resources -from google.cloud.kms_v1.types import service -from google.cloud.location import locations_pb2 -from google.iam.v1 import iam_policy_pb2 # type: ignore -from google.iam.v1 import options_pb2 # type: ignore -from google.iam.v1 import policy_pb2 # type: ignore -from google.longrunning import operations_pb2 # type: ignore -from google.oauth2 import service_account -from google.protobuf import duration_pb2 # type: ignore -from google.protobuf import field_mask_pb2 # type: ignore -from google.protobuf import timestamp_pb2 # type: ignore -from google.protobuf import wrappers_pb2 # type: ignore -import google.auth - - -async def mock_async_gen(data, chunk_size=1): - for i in range(0, len(data)): # pragma: NO COVER - chunk = data[i : i + chunk_size] - yield chunk.encode("utf-8") - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - -# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. -# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. -def async_anonymous_credentials(): - if HAS_GOOGLE_AUTH_AIO: - return ga_credentials_async.AnonymousCredentials() - return ga_credentials.AnonymousCredentials() - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT - -# If default endpoint template is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint template so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint_template(client): - return "test.{UNIVERSE_DOMAIN}" if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) else client._DEFAULT_ENDPOINT_TEMPLATE - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert KeyManagementServiceClient._get_default_mtls_endpoint(None) is None - assert KeyManagementServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - assert KeyManagementServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint - assert KeyManagementServiceClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint - assert KeyManagementServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint - assert KeyManagementServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - -def test__read_environment_variables(): - assert KeyManagementServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - assert KeyManagementServiceClient._read_environment_variables() == (True, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - assert KeyManagementServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - KeyManagementServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - assert KeyManagementServiceClient._read_environment_variables() == (False, "never", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - assert KeyManagementServiceClient._read_environment_variables() == (False, "always", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): - assert KeyManagementServiceClient._read_environment_variables() == (False, "auto", None) - - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - KeyManagementServiceClient._read_environment_variables() - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): - assert KeyManagementServiceClient._read_environment_variables() == (False, "auto", "foo.com") - -def test__get_client_cert_source(): - mock_provided_cert_source = mock.Mock() - mock_default_cert_source = mock.Mock() - - assert KeyManagementServiceClient._get_client_cert_source(None, False) is None - assert KeyManagementServiceClient._get_client_cert_source(mock_provided_cert_source, False) is None - assert KeyManagementServiceClient._get_client_cert_source(mock_provided_cert_source, True) == mock_provided_cert_source - - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_default_cert_source): - assert KeyManagementServiceClient._get_client_cert_source(None, True) is mock_default_cert_source - assert KeyManagementServiceClient._get_client_cert_source(mock_provided_cert_source, "true") is mock_provided_cert_source - -@mock.patch.object(KeyManagementServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceClient)) -@mock.patch.object(KeyManagementServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceAsyncClient)) -def test__get_api_endpoint(): - api_override = "foo.com" - mock_client_cert_source = mock.Mock() - default_universe = KeyManagementServiceClient._DEFAULT_UNIVERSE - default_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - assert KeyManagementServiceClient._get_api_endpoint(api_override, mock_client_cert_source, default_universe, "always") == api_override - assert KeyManagementServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "auto") == KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT - assert KeyManagementServiceClient._get_api_endpoint(None, None, default_universe, "auto") == default_endpoint - assert KeyManagementServiceClient._get_api_endpoint(None, None, default_universe, "always") == KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT - assert KeyManagementServiceClient._get_api_endpoint(None, mock_client_cert_source, default_universe, "always") == KeyManagementServiceClient.DEFAULT_MTLS_ENDPOINT - assert KeyManagementServiceClient._get_api_endpoint(None, None, mock_universe, "never") == mock_endpoint - assert KeyManagementServiceClient._get_api_endpoint(None, None, default_universe, "never") == default_endpoint - - with pytest.raises(MutualTLSChannelError) as excinfo: - KeyManagementServiceClient._get_api_endpoint(None, mock_client_cert_source, mock_universe, "auto") - assert str(excinfo.value) == "mTLS is not supported in any universe other than googleapis.com." - - -def test__get_universe_domain(): - client_universe_domain = "foo.com" - universe_domain_env = "bar.com" - - assert KeyManagementServiceClient._get_universe_domain(client_universe_domain, universe_domain_env) == client_universe_domain - assert KeyManagementServiceClient._get_universe_domain(None, universe_domain_env) == universe_domain_env - assert KeyManagementServiceClient._get_universe_domain(None, None) == KeyManagementServiceClient._DEFAULT_UNIVERSE - - with pytest.raises(ValueError) as excinfo: - KeyManagementServiceClient._get_universe_domain("", None) - assert str(excinfo.value) == "Universe Domain cannot be an empty string." - - -@pytest.mark.parametrize("client_class,transport_name", [ - (KeyManagementServiceClient, "grpc"), - (KeyManagementServiceAsyncClient, "grpc_asyncio"), - (KeyManagementServiceClient, "rest"), -]) -def test_key_management_service_client_from_service_account_info(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_info') as factory: - factory.return_value = creds - info = {"valid": True} - client = client_class.from_service_account_info(info, transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudkms.googleapis.com' - ) - - -@pytest.mark.parametrize("transport_class,transport_name", [ - (transports.KeyManagementServiceGrpcTransport, "grpc"), - (transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (transports.KeyManagementServiceRestTransport, "rest"), -]) -def test_key_management_service_client_service_account_always_use_jwt(transport_class, transport_name): - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=True) - use_jwt.assert_called_once_with(True) - - with mock.patch.object(service_account.Credentials, 'with_always_use_jwt_access', create=True) as use_jwt: - creds = service_account.Credentials(None, None, None) - transport = transport_class(credentials=creds, always_use_jwt_access=False) - use_jwt.assert_not_called() - - -@pytest.mark.parametrize("client_class,transport_name", [ - (KeyManagementServiceClient, "grpc"), - (KeyManagementServiceAsyncClient, "grpc_asyncio"), - (KeyManagementServiceClient, "rest"), -]) -def test_key_management_service_client_from_service_account_file(client_class, transport_name): - creds = ga_credentials.AnonymousCredentials() - with mock.patch.object(service_account.Credentials, 'from_service_account_file') as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - client = client_class.from_service_account_json("dummy/file/path.json", transport=transport_name) - assert client.transport._credentials == creds - assert isinstance(client, client_class) - - assert client.transport._host == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else - 'https://cloudkms.googleapis.com' - ) - - -def test_key_management_service_client_get_transport_class(): - transport = KeyManagementServiceClient.get_transport_class() - available_transports = [ - transports.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceRestTransport, - ] - assert transport in available_transports - - transport = KeyManagementServiceClient.get_transport_class("grpc") - assert transport == transports.KeyManagementServiceGrpcTransport - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc"), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (KeyManagementServiceClient, transports.KeyManagementServiceRestTransport, "rest"), -]) -@mock.patch.object(KeyManagementServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceClient)) -@mock.patch.object(KeyManagementServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceAsyncClient)) -def test_key_management_service_client_client_options(client_class, transport_class, transport_name): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(KeyManagementServiceClient, '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(KeyManagementServiceClient, 'get_transport_class') as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name, client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client = client_class(transport=transport_name) - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - - # Check the case quota_project_id is provided - options = client_options.ClientOptions(quota_project_id="octopus") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - # Check the case api_endpoint is provided - options = client_options.ClientOptions(api_audience="https://language.googleapis.com") - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience="https://language.googleapis.com" - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,use_client_cert_env", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", "true"), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", "true"), - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", "false"), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", "false"), - (KeyManagementServiceClient, transports.KeyManagementServiceRestTransport, "rest", "true"), - (KeyManagementServiceClient, transports.KeyManagementServiceRestTransport, "rest", "false"), -]) -@mock.patch.object(KeyManagementServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceClient)) -@mock.patch.object(KeyManagementServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceAsyncClient)) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_key_management_service_client_mtls_env_auto(client_class, transport_class, transport_name, use_client_cert_env): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - options = client_options.ClientOptions(client_cert_source=client_cert_source_callback) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - - if use_client_cert_env == "false": - expected_client_cert_source = None - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - else: - expected_client_cert_source = client_cert_source_callback - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=client_cert_source_callback): - if use_client_cert_env == "false": - expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE) - expected_client_cert_source = None - else: - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_client_cert_source = client_cert_source_callback - - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - client_cert_source_for_mtls=expected_client_cert_source, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}): - with mock.patch.object(transport_class, '__init__') as patched: - with mock.patch("google.auth.transport.mtls.has_default_client_cert_source", return_value=False): - patched.return_value = None - client = client_class(transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - -@pytest.mark.parametrize("client_class", [ - KeyManagementServiceClient, KeyManagementServiceAsyncClient -]) -@mock.patch.object(KeyManagementServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KeyManagementServiceClient)) -@mock.patch.object(KeyManagementServiceAsyncClient, "DEFAULT_ENDPOINT", modify_default_endpoint(KeyManagementServiceAsyncClient)) -def test_key_management_service_client_get_mtls_endpoint_and_cert_source(client_class): - mock_client_cert_source = mock.Mock() - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source == mock_client_cert_source - - # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): - mock_client_cert_source = mock.Mock() - mock_api_endpoint = "foo" - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint) - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(options) - assert api_endpoint == mock_api_endpoint - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=False): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_ENDPOINT - assert cert_source is None - - # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch('google.auth.transport.mtls.has_default_client_cert_source', return_value=True): - with mock.patch('google.auth.transport.mtls.default_client_cert_source', return_value=mock_client_cert_source): - api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() - assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - assert cert_source == mock_client_cert_source - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" - - # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}): - with pytest.raises(ValueError) as excinfo: - client_class.get_mtls_endpoint_and_cert_source() - - assert str(excinfo.value) == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" - -@pytest.mark.parametrize("client_class", [ - KeyManagementServiceClient, KeyManagementServiceAsyncClient -]) -@mock.patch.object(KeyManagementServiceClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceClient)) -@mock.patch.object(KeyManagementServiceAsyncClient, "_DEFAULT_ENDPOINT_TEMPLATE", modify_default_endpoint_template(KeyManagementServiceAsyncClient)) -def test_key_management_service_client_client_api_endpoint(client_class): - mock_client_cert_source = client_cert_source_callback - api_override = "foo.com" - default_universe = KeyManagementServiceClient._DEFAULT_UNIVERSE - default_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=default_universe) - mock_universe = "bar.com" - mock_endpoint = KeyManagementServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=mock_universe) - - # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", - # use ClientOptions.api_endpoint as the api endpoint regardless. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"): - options = client_options.ClientOptions(client_cert_source=mock_client_cert_source, api_endpoint=api_override) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == api_override - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", - # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - client = client_class(credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT - - # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), - # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, - # and ClientOptions.universe_domain="bar.com", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. - options = client_options.ClientOptions() - universe_exists = hasattr(options, "universe_domain") - if universe_exists: - options = client_options.ClientOptions(universe_domain=mock_universe) - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - else: - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == (mock_endpoint if universe_exists else default_endpoint) - assert client.universe_domain == (mock_universe if universe_exists else default_universe) - - # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", - # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. - options = client_options.ClientOptions() - if hasattr(options, "universe_domain"): - delattr(options, "universe_domain") - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - client = client_class(client_options=options, credentials=ga_credentials.AnonymousCredentials()) - assert client.api_endpoint == default_endpoint - - -@pytest.mark.parametrize("client_class,transport_class,transport_name", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc"), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio"), - (KeyManagementServiceClient, transports.KeyManagementServiceRestTransport, "rest"), -]) -def test_key_management_service_client_client_options_scopes(client_class, transport_class, transport_name): - # Check the case scopes are provided. - options = client_options.ClientOptions( - scopes=["1", "2"], - ) - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=["1", "2"], - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -@pytest.mark.parametrize("client_class,transport_class,transport_name,grpc_helpers", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", grpc_helpers), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), - (KeyManagementServiceClient, transports.KeyManagementServiceRestTransport, "rest", None), -]) -def test_key_management_service_client_client_options_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - -def test_key_management_service_client_client_options_from_dict(): - with mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceGrpcTransport.__init__') as grpc_transport: - grpc_transport.return_value = None - client = KeyManagementServiceClient( - 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", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport, "grpc", grpc_helpers), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport, "grpc_asyncio", grpc_helpers_async), -]) -def test_key_management_service_client_create_channel_credentials_file(client_class, transport_class, transport_name, grpc_helpers): - # Check the case credentials file is provided. - options = client_options.ClientOptions( - credentials_file="credentials.json" - ) - - with mock.patch.object(transport_class, '__init__') as patched: - patched.return_value = None - client = client_class(client_options=options, transport=transport_name) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) - - # test that the credentials from file are saved and used as the credentials. - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel" - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - file_creds = ga_credentials.AnonymousCredentials() - load_creds.return_value = (file_creds, None) - adc.return_value = (creds, None) - client = client_class(client_options=options, transport=transport_name) - create_channel.assert_called_with( - "cloudkms.googleapis.com:443", - credentials=file_creds, - credentials_file=None, - quota_project_id=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - scopes=None, - default_host="cloudkms.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("request_type", [ - service.ListKeyRingsRequest, - dict, -]) -def test_list_key_rings(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_key_rings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListKeyRingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_key_rings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.ListKeyRingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKeyRingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_key_rings_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.ListKeyRingsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_key_rings(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListKeyRingsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_key_rings_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_key_rings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_key_rings] = mock_rpc - request = {} - client.list_key_rings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_key_rings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_key_rings_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_key_rings in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_key_rings] = mock_rpc - - request = {} - await client.list_key_rings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_key_rings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_key_rings_async(transport: str = 'grpc_asyncio', request_type=service.ListKeyRingsRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_key_rings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.ListKeyRingsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKeyRingsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_key_rings_async_from_dict(): - await test_list_key_rings_async(request_type=dict) - -def test_list_key_rings_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListKeyRingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - call.return_value = service.ListKeyRingsResponse() - client.list_key_rings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_key_rings_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListKeyRingsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse()) - await client.list_key_rings(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_key_rings_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListKeyRingsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_key_rings( - 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_key_rings_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_key_rings( - service.ListKeyRingsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_key_rings_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListKeyRingsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_key_rings( - 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_key_rings_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_key_rings( - service.ListKeyRingsRequest(), - parent='parent_value', - ) - - -def test_list_key_rings_pager(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_key_rings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - resources.KeyRing(), - ], - next_page_token='abc', - ), - service.ListKeyRingsResponse( - key_rings=[], - next_page_token='def', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - ], - next_page_token='ghi', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_key_rings(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.KeyRing) - for i in results) -def test_list_key_rings_pages(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_key_rings), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - resources.KeyRing(), - ], - next_page_token='abc', - ), - service.ListKeyRingsResponse( - key_rings=[], - next_page_token='def', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - ], - next_page_token='ghi', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - ], - ), - RuntimeError, - ) - pages = list(client.list_key_rings(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_key_rings_async_pager(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - resources.KeyRing(), - ], - next_page_token='abc', - ), - service.ListKeyRingsResponse( - key_rings=[], - next_page_token='def', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - ], - next_page_token='ghi', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_key_rings(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, resources.KeyRing) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_key_rings_async_pages(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - resources.KeyRing(), - ], - next_page_token='abc', - ), - service.ListKeyRingsResponse( - key_rings=[], - next_page_token='def', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - ], - next_page_token='ghi', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_key_rings(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - service.ListCryptoKeysRequest, - dict, -]) -def test_list_crypto_keys(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crypto_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeysResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_crypto_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.ListCryptoKeysRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCryptoKeysPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_crypto_keys_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.ListCryptoKeysRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_crypto_keys(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCryptoKeysRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_crypto_keys_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_crypto_keys in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_crypto_keys] = mock_rpc - request = {} - client.list_crypto_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_crypto_keys(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_crypto_keys_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_crypto_keys in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_crypto_keys] = mock_rpc - - request = {} - await client.list_crypto_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_crypto_keys(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_crypto_keys_async(transport: str = 'grpc_asyncio', request_type=service.ListCryptoKeysRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_crypto_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.ListCryptoKeysRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCryptoKeysAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_crypto_keys_async_from_dict(): - await test_list_crypto_keys_async(request_type=dict) - -def test_list_crypto_keys_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListCryptoKeysRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - call.return_value = service.ListCryptoKeysResponse() - client.list_crypto_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_list_crypto_keys_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListCryptoKeysRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse()) - await client.list_crypto_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -def test_list_crypto_keys_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeysResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_crypto_keys( - 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_crypto_keys_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_crypto_keys( - service.ListCryptoKeysRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_crypto_keys_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeysResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_crypto_keys( - 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_crypto_keys_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_crypto_keys( - service.ListCryptoKeysRequest(), - parent='parent_value', - ) - - -def test_list_crypto_keys_pager(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_crypto_keys), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - resources.CryptoKey(), - ], - next_page_token='abc', - ), - service.ListCryptoKeysResponse( - crypto_keys=[], - next_page_token='def', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_crypto_keys(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.CryptoKey) - for i in results) -def test_list_crypto_keys_pages(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_crypto_keys), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - resources.CryptoKey(), - ], - next_page_token='abc', - ), - service.ListCryptoKeysResponse( - crypto_keys=[], - next_page_token='def', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - ], - ), - RuntimeError, - ) - pages = list(client.list_crypto_keys(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_crypto_keys_async_pager(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - resources.CryptoKey(), - ], - next_page_token='abc', - ), - service.ListCryptoKeysResponse( - crypto_keys=[], - next_page_token='def', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_crypto_keys(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, resources.CryptoKey) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_crypto_keys_async_pages(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - resources.CryptoKey(), - ], - next_page_token='abc', - ), - service.ListCryptoKeysResponse( - crypto_keys=[], - next_page_token='def', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_crypto_keys(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - service.ListCryptoKeyVersionsRequest, - dict, -]) -def test_list_crypto_key_versions(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crypto_key_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeyVersionsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_crypto_key_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.ListCryptoKeyVersionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCryptoKeyVersionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_crypto_key_versions_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.ListCryptoKeyVersionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_crypto_key_versions(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListCryptoKeyVersionsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_crypto_key_versions_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_crypto_key_versions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_crypto_key_versions] = mock_rpc - request = {} - client.list_crypto_key_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_crypto_key_versions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_crypto_key_versions_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_crypto_key_versions in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_crypto_key_versions] = mock_rpc - - request = {} - await client.list_crypto_key_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_crypto_key_versions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_crypto_key_versions_async(transport: str = 'grpc_asyncio', request_type=service.ListCryptoKeyVersionsRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_crypto_key_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.ListCryptoKeyVersionsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCryptoKeyVersionsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_crypto_key_versions_async_from_dict(): - await test_list_crypto_key_versions_async(request_type=dict) - -def test_list_crypto_key_versions_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListCryptoKeyVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - call.return_value = service.ListCryptoKeyVersionsResponse() - client.list_crypto_key_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_crypto_key_versions_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListCryptoKeyVersionsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse()) - await client.list_crypto_key_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_crypto_key_versions_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeyVersionsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_crypto_key_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_crypto_key_versions_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_crypto_key_versions( - service.ListCryptoKeyVersionsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_crypto_key_versions_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListCryptoKeyVersionsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_crypto_key_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_crypto_key_versions_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_crypto_key_versions( - service.ListCryptoKeyVersionsRequest(), - parent='parent_value', - ) - - -def test_list_crypto_key_versions_pager(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_crypto_key_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - next_page_token='abc', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[], - next_page_token='def', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_crypto_key_versions(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.CryptoKeyVersion) - for i in results) -def test_list_crypto_key_versions_pages(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_crypto_key_versions), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - next_page_token='abc', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[], - next_page_token='def', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - ), - RuntimeError, - ) - pages = list(client.list_crypto_key_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_crypto_key_versions_async_pager(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - next_page_token='abc', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[], - next_page_token='def', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_crypto_key_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, resources.CryptoKeyVersion) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_crypto_key_versions_async_pages(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - next_page_token='abc', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[], - next_page_token='def', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_crypto_key_versions(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - service.ListImportJobsRequest, - dict, -]) -def test_list_import_jobs(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_import_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListImportJobsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - response = client.list_import_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.ListImportJobsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListImportJobsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -def test_list_import_jobs_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.ListImportJobsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.list_import_jobs(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ListImportJobsRequest( - parent='parent_value', - page_token='page_token_value', - filter='filter_value', - order_by='order_by_value', - ) - -def test_list_import_jobs_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_import_jobs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_import_jobs] = mock_rpc - request = {} - client.list_import_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_import_jobs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_import_jobs_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.list_import_jobs in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.list_import_jobs] = mock_rpc - - request = {} - await client.list_import_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.list_import_jobs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_list_import_jobs_async(transport: str = 'grpc_asyncio', request_type=service.ListImportJobsRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - response = await client.list_import_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.ListImportJobsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListImportJobsAsyncPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_import_jobs_async_from_dict(): - await test_list_import_jobs_async(request_type=dict) - -def test_list_import_jobs_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListImportJobsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - call.return_value = service.ListImportJobsResponse() - client.list_import_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_import_jobs_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ListImportJobsRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse()) - await client.list_import_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_import_jobs_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListImportJobsResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_import_jobs( - 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_import_jobs_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_import_jobs( - service.ListImportJobsRequest(), - parent='parent_value', - ) - -@pytest.mark.asyncio -async def test_list_import_jobs_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListImportJobsResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.list_import_jobs( - 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_import_jobs_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_import_jobs( - service.ListImportJobsRequest(), - parent='parent_value', - ) - - -def test_list_import_jobs_pager(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_import_jobs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - resources.ImportJob(), - ], - next_page_token='abc', - ), - service.ListImportJobsResponse( - import_jobs=[], - next_page_token='def', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - ], - next_page_token='ghi', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(( - ('parent', ''), - )), - ) - pager = client.list_import_jobs(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.ImportJob) - for i in results) -def test_list_import_jobs_pages(transport_name: str = "grpc"): - client = KeyManagementServiceClient( - 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_import_jobs), - '__call__') as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - resources.ImportJob(), - ], - next_page_token='abc', - ), - service.ListImportJobsResponse( - import_jobs=[], - next_page_token='def', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - ], - next_page_token='ghi', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - ], - ), - RuntimeError, - ) - pages = list(client.list_import_jobs(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_import_jobs_async_pager(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - resources.ImportJob(), - ], - next_page_token='abc', - ), - service.ListImportJobsResponse( - import_jobs=[], - next_page_token='def', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - ], - next_page_token='ghi', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_import_jobs(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, resources.ImportJob) - for i in responses) - - -@pytest.mark.asyncio -async def test_list_import_jobs_async_pages(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__', new_callable=mock.AsyncMock) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - resources.ImportJob(), - ], - next_page_token='abc', - ), - service.ListImportJobsResponse( - import_jobs=[], - next_page_token='def', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - ], - next_page_token='ghi', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_import_jobs(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - -@pytest.mark.parametrize("request_type", [ - service.GetKeyRingRequest, - dict, -]) -def test_get_key_ring(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing( - name='name_value', - ) - response = client.get_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetKeyRingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.KeyRing) - assert response.name == 'name_value' - - -def test_get_key_ring_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetKeyRingRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_key_ring(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetKeyRingRequest( - name='name_value', - ) - -def test_get_key_ring_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_key_ring in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_key_ring] = mock_rpc - request = {} - client.get_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_key_ring(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_key_ring_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_key_ring in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_key_ring] = mock_rpc - - request = {} - await client.get_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_key_ring(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_key_ring_async(transport: str = 'grpc_asyncio', request_type=service.GetKeyRingRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( - name='name_value', - )) - response = await client.get_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GetKeyRingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.KeyRing) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_get_key_ring_async_from_dict(): - await test_get_key_ring_async(request_type=dict) - -def test_get_key_ring_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetKeyRingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - call.return_value = resources.KeyRing() - client.get_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_key_ring_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetKeyRingRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) - await client.get_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_key_ring_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_key_ring( - 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_key_ring_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_key_ring( - service.GetKeyRingRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_key_ring_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_key_ring( - 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_key_ring_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_key_ring( - service.GetKeyRingRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.GetCryptoKeyRequest, - dict, -]) -def test_get_crypto_key(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - ) - response = client.get_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetCryptoKeyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -def test_get_crypto_key_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetCryptoKeyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_crypto_key(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCryptoKeyRequest( - name='name_value', - ) - -def test_get_crypto_key_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_crypto_key in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_crypto_key] = mock_rpc - request = {} - client.get_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_crypto_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_crypto_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_crypto_key in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_crypto_key] = mock_rpc - - request = {} - await client.get_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_crypto_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.GetCryptoKeyRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - )) - response = await client.get_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GetCryptoKeyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@pytest.mark.asyncio -async def test_get_crypto_key_async_from_dict(): - await test_get_crypto_key_async(request_type=dict) - -def test_get_crypto_key_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetCryptoKeyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.get_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crypto_key_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetCryptoKeyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - await client.get_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crypto_key_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_crypto_key( - 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_crypto_key_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_crypto_key( - service.GetCryptoKeyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_crypto_key_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_crypto_key( - 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_crypto_key_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_crypto_key( - service.GetCryptoKeyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.GetCryptoKeyVersionRequest, - dict, -]) -def test_get_crypto_key_version(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - response = client.get_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -def test_get_crypto_key_version_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetCryptoKeyVersionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_crypto_key_version(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetCryptoKeyVersionRequest( - name='name_value', - ) - -def test_get_crypto_key_version_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_crypto_key_version] = mock_rpc - request = {} - client.get_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_crypto_key_version in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_crypto_key_version] = mock_rpc - - request = {} - await client.get_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.GetCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - response = await client.get_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GetCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_get_crypto_key_version_async_from_dict(): - await test_get_crypto_key_version_async(request_type=dict) - -def test_get_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetCryptoKeyVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.get_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetCryptoKeyVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.get_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crypto_key_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_crypto_key_version( - 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_crypto_key_version_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_crypto_key_version( - service.GetCryptoKeyVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_crypto_key_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_crypto_key_version( - 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_crypto_key_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_crypto_key_version( - service.GetCryptoKeyVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.GetPublicKeyRequest, - dict, -]) -def test_get_public_key(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_public_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.PublicKey( - pem='pem_value', - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - name='name_value', - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.get_public_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetPublicKeyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.PublicKey) - assert response.pem == 'pem_value' - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.name == 'name_value' - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -def test_get_public_key_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetPublicKeyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_public_key(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetPublicKeyRequest( - name='name_value', - ) - -def test_get_public_key_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_public_key in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_public_key] = mock_rpc - request = {} - client.get_public_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_public_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_public_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_public_key in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_public_key] = mock_rpc - - request = {} - await client.get_public_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_public_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_public_key_async(transport: str = 'grpc_asyncio', request_type=service.GetPublicKeyRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey( - pem='pem_value', - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - name='name_value', - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.get_public_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GetPublicKeyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.PublicKey) - assert response.pem == 'pem_value' - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.name == 'name_value' - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_get_public_key_async_from_dict(): - await test_get_public_key_async(request_type=dict) - -def test_get_public_key_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetPublicKeyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - call.return_value = resources.PublicKey() - client.get_public_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_public_key_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetPublicKeyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey()) - await client.get_public_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_public_key_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.PublicKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_public_key( - 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_public_key_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_public_key( - service.GetPublicKeyRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_public_key_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.PublicKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_public_key( - 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_public_key_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_public_key( - service.GetPublicKeyRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.GetImportJobRequest, - dict, -]) -def test_get_import_job(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - ) - response = client.get_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GetImportJobRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) - assert response.name == 'name_value' - assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - - -def test_get_import_job_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GetImportJobRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.get_import_job(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetImportJobRequest( - name='name_value', - ) - -def test_get_import_job_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_import_job in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_import_job] = mock_rpc - request = {} - client.get_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_import_job(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_import_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.get_import_job in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.get_import_job] = mock_rpc - - request = {} - await client.get_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.get_import_job(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_get_import_job_async(transport: str = 'grpc_asyncio', request_type=service.GetImportJobRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - )) - response = await client.get_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GetImportJobRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) - assert response.name == 'name_value' - assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - - -@pytest.mark.asyncio -async def test_get_import_job_async_from_dict(): - await test_get_import_job_async(request_type=dict) - -def test_get_import_job_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetImportJobRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - call.return_value = resources.ImportJob() - client.get_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_import_job_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetImportJobRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) - await client.get_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_import_job_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_import_job( - 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_import_job_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_import_job( - service.GetImportJobRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_get_import_job_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.get_import_job( - 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_import_job_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.get_import_job( - service.GetImportJobRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.CreateKeyRingRequest, - dict, -]) -def test_create_key_ring(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing( - name='name_value', - ) - response = client.create_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.CreateKeyRingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.KeyRing) - assert response.name == 'name_value' - - -def test_create_key_ring_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.CreateKeyRingRequest( - parent='parent_value', - key_ring_id='key_ring_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_key_ring(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateKeyRingRequest( - parent='parent_value', - key_ring_id='key_ring_id_value', - ) - -def test_create_key_ring_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_key_ring in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_key_ring] = mock_rpc - request = {} - client.create_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_key_ring(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_key_ring_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_key_ring in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_key_ring] = mock_rpc - - request = {} - await client.create_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_key_ring(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_key_ring_async(transport: str = 'grpc_asyncio', request_type=service.CreateKeyRingRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( - name='name_value', - )) - response = await client.create_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.CreateKeyRingRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.KeyRing) - assert response.name == 'name_value' - - -@pytest.mark.asyncio -async def test_create_key_ring_async_from_dict(): - await test_create_key_ring_async(request_type=dict) - -def test_create_key_ring_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateKeyRingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - call.return_value = resources.KeyRing() - client.create_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_key_ring_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateKeyRingRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) - await client.create_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_key_ring_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_key_ring( - parent='parent_value', - key_ring_id='key_ring_id_value', - key_ring=resources.KeyRing(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].key_ring_id - mock_val = 'key_ring_id_value' - assert arg == mock_val - arg = args[0].key_ring - mock_val = resources.KeyRing(name='name_value') - assert arg == mock_val - - -def test_create_key_ring_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_key_ring( - service.CreateKeyRingRequest(), - parent='parent_value', - key_ring_id='key_ring_id_value', - key_ring=resources.KeyRing(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_key_ring_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.KeyRing() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_key_ring( - parent='parent_value', - key_ring_id='key_ring_id_value', - key_ring=resources.KeyRing(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].key_ring_id - mock_val = 'key_ring_id_value' - assert arg == mock_val - arg = args[0].key_ring - mock_val = resources.KeyRing(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_key_ring_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_key_ring( - service.CreateKeyRingRequest(), - parent='parent_value', - key_ring_id='key_ring_id_value', - key_ring=resources.KeyRing(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - service.CreateCryptoKeyRequest, - dict, -]) -def test_create_crypto_key(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - ) - response = client.create_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.CreateCryptoKeyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -def test_create_crypto_key_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.CreateCryptoKeyRequest( - parent='parent_value', - crypto_key_id='crypto_key_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_crypto_key(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCryptoKeyRequest( - parent='parent_value', - crypto_key_id='crypto_key_id_value', - ) - -def test_create_crypto_key_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_crypto_key in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_crypto_key] = mock_rpc - request = {} - client.create_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_crypto_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_crypto_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_crypto_key in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_crypto_key] = mock_rpc - - request = {} - await client.create_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_crypto_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.CreateCryptoKeyRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - )) - response = await client.create_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.CreateCryptoKeyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@pytest.mark.asyncio -async def test_create_crypto_key_async_from_dict(): - await test_create_crypto_key_async(request_type=dict) - -def test_create_crypto_key_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateCryptoKeyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.create_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_crypto_key_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateCryptoKeyRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - await client.create_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_crypto_key_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_crypto_key( - parent='parent_value', - crypto_key_id='crypto_key_id_value', - crypto_key=resources.CryptoKey(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].crypto_key_id - mock_val = 'crypto_key_id_value' - assert arg == mock_val - arg = args[0].crypto_key - mock_val = resources.CryptoKey(name='name_value') - assert arg == mock_val - - -def test_create_crypto_key_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_crypto_key( - service.CreateCryptoKeyRequest(), - parent='parent_value', - crypto_key_id='crypto_key_id_value', - crypto_key=resources.CryptoKey(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_crypto_key_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_crypto_key( - parent='parent_value', - crypto_key_id='crypto_key_id_value', - crypto_key=resources.CryptoKey(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].crypto_key_id - mock_val = 'crypto_key_id_value' - assert arg == mock_val - arg = args[0].crypto_key - mock_val = resources.CryptoKey(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_crypto_key_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_crypto_key( - service.CreateCryptoKeyRequest(), - parent='parent_value', - crypto_key_id='crypto_key_id_value', - crypto_key=resources.CryptoKey(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - service.CreateCryptoKeyVersionRequest, - dict, -]) -def test_create_crypto_key_version(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - response = client.create_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.CreateCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -def test_create_crypto_key_version_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.CreateCryptoKeyVersionRequest( - parent='parent_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_crypto_key_version(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateCryptoKeyVersionRequest( - parent='parent_value', - ) - -def test_create_crypto_key_version_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_crypto_key_version] = mock_rpc - request = {} - client.create_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_crypto_key_version in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_crypto_key_version] = mock_rpc - - request = {} - await client.create_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.CreateCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - response = await client.create_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.CreateCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_create_crypto_key_version_async_from_dict(): - await test_create_crypto_key_version_async(request_type=dict) - -def test_create_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateCryptoKeyVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.create_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateCryptoKeyVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.create_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_crypto_key_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_crypto_key_version( - parent='parent_value', - crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version - mock_val = resources.CryptoKeyVersion(name='name_value') - assert arg == mock_val - - -def test_create_crypto_key_version_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_crypto_key_version( - service.CreateCryptoKeyVersionRequest(), - parent='parent_value', - crypto_key_version=resources.CryptoKeyVersion(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_crypto_key_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_crypto_key_version( - parent='parent_value', - crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version - mock_val = resources.CryptoKeyVersion(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_crypto_key_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_crypto_key_version( - service.CreateCryptoKeyVersionRequest(), - parent='parent_value', - crypto_key_version=resources.CryptoKeyVersion(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - service.ImportCryptoKeyVersionRequest, - dict, -]) -def test_import_crypto_key_version(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - response = client.import_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.ImportCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -def test_import_crypto_key_version_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.ImportCryptoKeyVersionRequest( - parent='parent_value', - crypto_key_version='crypto_key_version_value', - import_job='import_job_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_crypto_key_version), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.import_crypto_key_version(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.ImportCryptoKeyVersionRequest( - parent='parent_value', - crypto_key_version='crypto_key_version_value', - import_job='import_job_value', - ) - -def test_import_crypto_key_version_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.import_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.import_crypto_key_version] = mock_rpc - request = {} - client.import_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.import_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_import_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.import_crypto_key_version in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.import_crypto_key_version] = mock_rpc - - request = {} - await client.import_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.import_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_import_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.ImportCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - response = await client.import_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.ImportCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_import_crypto_key_version_async_from_dict(): - await test_import_crypto_key_version_async(request_type=dict) - -def test_import_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ImportCryptoKeyVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.import_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_import_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.ImportCryptoKeyVersionRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.import_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.import_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'parent=parent_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - service.CreateImportJobRequest, - dict, -]) -def test_create_import_job(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - ) - response = client.create_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.CreateImportJobRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) - assert response.name == 'name_value' - assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - - -def test_create_import_job_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.CreateImportJobRequest( - parent='parent_value', - import_job_id='import_job_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.create_import_job(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateImportJobRequest( - parent='parent_value', - import_job_id='import_job_id_value', - ) - -def test_create_import_job_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_import_job in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_import_job] = mock_rpc - request = {} - client.create_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_import_job(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_import_job_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.create_import_job in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.create_import_job] = mock_rpc - - request = {} - await client.create_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.create_import_job(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_create_import_job_async(transport: str = 'grpc_asyncio', request_type=service.CreateImportJobRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - )) - response = await client.create_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.CreateImportJobRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) - assert response.name == 'name_value' - assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - - -@pytest.mark.asyncio -async def test_create_import_job_async_from_dict(): - await test_create_import_job_async(request_type=dict) - -def test_create_import_job_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateImportJobRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - call.return_value = resources.ImportJob() - client.create_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.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_import_job_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.CreateImportJobRequest() - - request.parent = 'parent_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) - await client.create_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.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_import_job_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_import_job( - parent='parent_value', - import_job_id='import_job_id_value', - import_job=resources.ImportJob(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].import_job_id - mock_val = 'import_job_id_value' - assert arg == mock_val - arg = args[0].import_job - mock_val = resources.ImportJob(name='name_value') - assert arg == mock_val - - -def test_create_import_job_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_import_job( - service.CreateImportJobRequest(), - parent='parent_value', - import_job_id='import_job_id_value', - import_job=resources.ImportJob(name='name_value'), - ) - -@pytest.mark.asyncio -async def test_create_import_job_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_import_job( - parent='parent_value', - import_job_id='import_job_id_value', - import_job=resources.ImportJob(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].import_job_id - mock_val = 'import_job_id_value' - assert arg == mock_val - arg = args[0].import_job - mock_val = resources.ImportJob(name='name_value') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_create_import_job_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_import_job( - service.CreateImportJobRequest(), - parent='parent_value', - import_job_id='import_job_id_value', - import_job=resources.ImportJob(name='name_value'), - ) - - -@pytest.mark.parametrize("request_type", [ - service.UpdateCryptoKeyRequest, - dict, -]) -def test_update_crypto_key(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - ) - response = client.update_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -def test_update_crypto_key_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.UpdateCryptoKeyRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_crypto_key(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyRequest( - ) - -def test_update_crypto_key_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_crypto_key in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_crypto_key] = mock_rpc - request = {} - client.update_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_crypto_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_crypto_key_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_crypto_key in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_crypto_key] = mock_rpc - - request = {} - await client.update_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_crypto_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_crypto_key_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - )) - response = await client.update_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@pytest.mark.asyncio -async def test_update_crypto_key_async_from_dict(): - await test_update_crypto_key_async(request_type=dict) - -def test_update_crypto_key_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyRequest() - - request.crypto_key.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.update_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'crypto_key.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_crypto_key_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyRequest() - - request.crypto_key.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - await client.update_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'crypto_key.name=name_value', - ) in kw['metadata'] - - -def test_update_crypto_key_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_crypto_key( - crypto_key=resources.CryptoKey(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].crypto_key - mock_val = resources.CryptoKey(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_crypto_key_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_crypto_key( - service.UpdateCryptoKeyRequest(), - crypto_key=resources.CryptoKey(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_crypto_key_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_crypto_key( - crypto_key=resources.CryptoKey(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].crypto_key - mock_val = resources.CryptoKey(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_crypto_key_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_crypto_key( - service.UpdateCryptoKeyRequest(), - crypto_key=resources.CryptoKey(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - service.UpdateCryptoKeyVersionRequest, - dict, -]) -def test_update_crypto_key_version(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - response = client.update_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -def test_update_crypto_key_version_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.UpdateCryptoKeyVersionRequest( - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_crypto_key_version(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyVersionRequest( - ) - -def test_update_crypto_key_version_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_crypto_key_version] = mock_rpc - request = {} - client.update_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_crypto_key_version in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_crypto_key_version] = mock_rpc - - request = {} - await client.update_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - response = await client.update_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_update_crypto_key_version_async_from_dict(): - await test_update_crypto_key_version_async(request_type=dict) - -def test_update_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyVersionRequest() - - request.crypto_key_version.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.update_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'crypto_key_version.name=name_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_update_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyVersionRequest() - - request.crypto_key_version.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.update_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'crypto_key_version.name=name_value', - ) in kw['metadata'] - - -def test_update_crypto_key_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_crypto_key_version( - crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version - mock_val = resources.CryptoKeyVersion(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_crypto_key_version_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_crypto_key_version( - service.UpdateCryptoKeyVersionRequest(), - crypto_key_version=resources.CryptoKeyVersion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - -@pytest.mark.asyncio -async def test_update_crypto_key_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_crypto_key_version( - crypto_key_version=resources.CryptoKeyVersion(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].crypto_key_version - mock_val = resources.CryptoKeyVersion(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_crypto_key_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_crypto_key_version( - service.UpdateCryptoKeyVersionRequest(), - crypto_key_version=resources.CryptoKeyVersion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -@pytest.mark.parametrize("request_type", [ - service.UpdateCryptoKeyPrimaryVersionRequest, - dict, -]) -def test_update_crypto_key_primary_version(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an 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_crypto_key_primary_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - ) - response = client.update_crypto_key_primary_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyPrimaryVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -def test_update_crypto_key_primary_version_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.UpdateCryptoKeyPrimaryVersionRequest( - name='name_value', - crypto_key_version_id='crypto_key_version_id_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.update_crypto_key_primary_version(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateCryptoKeyPrimaryVersionRequest( - name='name_value', - crypto_key_version_id='crypto_key_version_id_value', - ) - -def test_update_crypto_key_primary_version_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_crypto_key_primary_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_crypto_key_primary_version] = mock_rpc - request = {} - client.update_crypto_key_primary_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_crypto_key_primary_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_crypto_key_primary_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.update_crypto_key_primary_version in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.update_crypto_key_primary_version] = mock_rpc - - request = {} - await client.update_crypto_key_primary_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.update_crypto_key_primary_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_update_crypto_key_primary_version_async(transport: str = 'grpc_asyncio', request_type=service.UpdateCryptoKeyPrimaryVersionRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - )) - response = await client.update_crypto_key_primary_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyPrimaryVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@pytest.mark.asyncio -async def test_update_crypto_key_primary_version_async_from_dict(): - await test_update_crypto_key_primary_version_async(request_type=dict) - -def test_update_crypto_key_primary_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyPrimaryVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.update_crypto_key_primary_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crypto_key_primary_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyPrimaryVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - await client.update_crypto_key_primary_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_crypto_key_primary_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_crypto_key_primary_version( - name='name_value', - crypto_key_version_id='crypto_key_version_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].crypto_key_version_id - mock_val = 'crypto_key_version_id_value' - assert arg == mock_val - - -def test_update_crypto_key_primary_version_flattened_error(): - client = KeyManagementServiceClient( - credentials=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_crypto_key_primary_version( - service.UpdateCryptoKeyPrimaryVersionRequest(), - name='name_value', - crypto_key_version_id='crypto_key_version_id_value', - ) - -@pytest.mark.asyncio -async def test_update_crypto_key_primary_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_crypto_key_primary_version( - name='name_value', - crypto_key_version_id='crypto_key_version_id_value', - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = 'name_value' - assert arg == mock_val - arg = args[0].crypto_key_version_id - mock_val = 'crypto_key_version_id_value' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_update_crypto_key_primary_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_crypto_key_primary_version( - service.UpdateCryptoKeyPrimaryVersionRequest(), - name='name_value', - crypto_key_version_id='crypto_key_version_id_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.DestroyCryptoKeyVersionRequest, - dict, -]) -def test_destroy_crypto_key_version(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - response = client.destroy_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.DestroyCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -def test_destroy_crypto_key_version_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.DestroyCryptoKeyVersionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.destroy_crypto_key_version(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DestroyCryptoKeyVersionRequest( - name='name_value', - ) - -def test_destroy_crypto_key_version_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.destroy_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.destroy_crypto_key_version] = mock_rpc - request = {} - client.destroy_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.destroy_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_destroy_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.destroy_crypto_key_version in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.destroy_crypto_key_version] = mock_rpc - - request = {} - await client.destroy_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.destroy_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_destroy_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.DestroyCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - response = await client.destroy_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.DestroyCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_destroy_crypto_key_version_async_from_dict(): - await test_destroy_crypto_key_version_async(request_type=dict) - -def test_destroy_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DestroyCryptoKeyVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.destroy_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_destroy_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DestroyCryptoKeyVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.destroy_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_destroy_crypto_key_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.destroy_crypto_key_version( - 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_destroy_crypto_key_version_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.destroy_crypto_key_version( - service.DestroyCryptoKeyVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_destroy_crypto_key_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.destroy_crypto_key_version( - 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_destroy_crypto_key_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.destroy_crypto_key_version( - service.DestroyCryptoKeyVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.RestoreCryptoKeyVersionRequest, - dict, -]) -def test_restore_crypto_key_version(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - response = client.restore_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.RestoreCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -def test_restore_crypto_key_version_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.RestoreCryptoKeyVersionRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.restore_crypto_key_version(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.RestoreCryptoKeyVersionRequest( - name='name_value', - ) - -def test_restore_crypto_key_version_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.restore_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.restore_crypto_key_version] = mock_rpc - request = {} - client.restore_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.restore_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_restore_crypto_key_version_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.restore_crypto_key_version in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.restore_crypto_key_version] = mock_rpc - - request = {} - await client.restore_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.restore_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_restore_crypto_key_version_async(transport: str = 'grpc_asyncio', request_type=service.RestoreCryptoKeyVersionRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - response = await client.restore_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.RestoreCryptoKeyVersionRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.asyncio -async def test_restore_crypto_key_version_async_from_dict(): - await test_restore_crypto_key_version_async(request_type=dict) - -def test_restore_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.RestoreCryptoKeyVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.restore_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_restore_crypto_key_version_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.RestoreCryptoKeyVersionRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - await client.restore_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_restore_crypto_key_version_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.restore_crypto_key_version( - 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_restore_crypto_key_version_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.restore_crypto_key_version( - service.RestoreCryptoKeyVersionRequest(), - name='name_value', - ) - -@pytest.mark.asyncio -async def test_restore_crypto_key_version_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.restore_crypto_key_version( - 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_restore_crypto_key_version_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.restore_crypto_key_version( - service.RestoreCryptoKeyVersionRequest(), - name='name_value', - ) - - -@pytest.mark.parametrize("request_type", [ - service.EncryptRequest, - dict, -]) -def test_encrypt(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.EncryptResponse( - name='name_value', - ciphertext=b'ciphertext_blob', - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.EncryptRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.EncryptResponse) - assert response.name == 'name_value' - assert response.ciphertext == b'ciphertext_blob' - assert response.verified_plaintext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -def test_encrypt_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.EncryptRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.encrypt(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.EncryptRequest( - name='name_value', - ) - -def test_encrypt_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.encrypt in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.encrypt] = mock_rpc - request = {} - client.encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.encrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_encrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.encrypt in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.encrypt] = mock_rpc - - request = {} - await client.encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.encrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_encrypt_async(transport: str = 'grpc_asyncio', request_type=service.EncryptRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse( - name='name_value', - ciphertext=b'ciphertext_blob', - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.EncryptRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.EncryptResponse) - assert response.name == 'name_value' - assert response.ciphertext == b'ciphertext_blob' - assert response.verified_plaintext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_encrypt_async_from_dict(): - await test_encrypt_async(request_type=dict) - -def test_encrypt_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.EncryptRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - call.return_value = service.EncryptResponse() - client.encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_encrypt_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.EncryptRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse()) - await client.encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_encrypt_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.EncryptResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.encrypt( - name='name_value', - plaintext=b'plaintext_blob', - ) - - # Establish that the 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].plaintext - mock_val = b'plaintext_blob' - assert arg == mock_val - - -def test_encrypt_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.encrypt( - service.EncryptRequest(), - name='name_value', - plaintext=b'plaintext_blob', - ) - -@pytest.mark.asyncio -async def test_encrypt_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.EncryptResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.encrypt( - name='name_value', - plaintext=b'plaintext_blob', - ) - - # Establish that 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].plaintext - mock_val = b'plaintext_blob' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_encrypt_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.encrypt( - service.EncryptRequest(), - name='name_value', - plaintext=b'plaintext_blob', - ) - - -@pytest.mark.parametrize("request_type", [ - service.DecryptRequest, - dict, -]) -def test_decrypt(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.DecryptResponse( - plaintext=b'plaintext_blob', - used_primary=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.DecryptRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.DecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.used_primary is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -def test_decrypt_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.DecryptRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.decrypt(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.DecryptRequest( - name='name_value', - ) - -def test_decrypt_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.decrypt in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.decrypt] = mock_rpc - request = {} - client.decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.decrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_decrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.decrypt in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.decrypt] = mock_rpc - - request = {} - await client.decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.decrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_decrypt_async(transport: str = 'grpc_asyncio', request_type=service.DecryptRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse( - plaintext=b'plaintext_blob', - used_primary=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.DecryptRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.DecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.used_primary is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_decrypt_async_from_dict(): - await test_decrypt_async(request_type=dict) - -def test_decrypt_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DecryptRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - call.return_value = service.DecryptResponse() - client.decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_decrypt_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.DecryptRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse()) - await client.decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_decrypt_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.DecryptResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.decrypt( - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - # Establish that the 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].ciphertext - mock_val = b'ciphertext_blob' - assert arg == mock_val - - -def test_decrypt_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.decrypt( - service.DecryptRequest(), - name='name_value', - ciphertext=b'ciphertext_blob', - ) - -@pytest.mark.asyncio -async def test_decrypt_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.DecryptResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.decrypt( - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - # Establish that 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].ciphertext - mock_val = b'ciphertext_blob' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_decrypt_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.decrypt( - service.DecryptRequest(), - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - -@pytest.mark.parametrize("request_type", [ - service.RawEncryptRequest, - dict, -]) -def test_raw_encrypt(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.raw_encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.RawEncryptResponse( - ciphertext=b'ciphertext_blob', - initialization_vector=b'initialization_vector_blob', - tag_length=1053, - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, - name='name_value', - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.raw_encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.RawEncryptRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.RawEncryptResponse) - assert response.ciphertext == b'ciphertext_blob' - assert response.initialization_vector == b'initialization_vector_blob' - assert response.tag_length == 1053 - assert response.verified_plaintext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.verified_initialization_vector_crc32c is True - assert response.name == 'name_value' - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -def test_raw_encrypt_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.RawEncryptRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.raw_encrypt), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.raw_encrypt(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.RawEncryptRequest( - name='name_value', - ) - -def test_raw_encrypt_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.raw_encrypt in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.raw_encrypt] = mock_rpc - request = {} - client.raw_encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.raw_encrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_raw_encrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.raw_encrypt in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.raw_encrypt] = mock_rpc - - request = {} - await client.raw_encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.raw_encrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_raw_encrypt_async(transport: str = 'grpc_asyncio', request_type=service.RawEncryptRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.raw_encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.RawEncryptResponse( - ciphertext=b'ciphertext_blob', - initialization_vector=b'initialization_vector_blob', - tag_length=1053, - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, - name='name_value', - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.raw_encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.RawEncryptRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.RawEncryptResponse) - assert response.ciphertext == b'ciphertext_blob' - assert response.initialization_vector == b'initialization_vector_blob' - assert response.tag_length == 1053 - assert response.verified_plaintext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.verified_initialization_vector_crc32c is True - assert response.name == 'name_value' - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_raw_encrypt_async_from_dict(): - await test_raw_encrypt_async(request_type=dict) - -def test_raw_encrypt_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.RawEncryptRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.raw_encrypt), - '__call__') as call: - call.return_value = service.RawEncryptResponse() - client.raw_encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_raw_encrypt_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.RawEncryptRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.raw_encrypt), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.RawEncryptResponse()) - await client.raw_encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - service.RawDecryptRequest, - dict, -]) -def test_raw_decrypt(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.raw_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.RawDecryptResponse( - plaintext=b'plaintext_blob', - protection_level=resources.ProtectionLevel.SOFTWARE, - verified_ciphertext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, - ) - response = client.raw_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.RawDecryptRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.RawDecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.verified_ciphertext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.verified_initialization_vector_crc32c is True - - -def test_raw_decrypt_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.RawDecryptRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.raw_decrypt), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.raw_decrypt(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.RawDecryptRequest( - name='name_value', - ) - -def test_raw_decrypt_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.raw_decrypt in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.raw_decrypt] = mock_rpc - request = {} - client.raw_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.raw_decrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_raw_decrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.raw_decrypt in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.raw_decrypt] = mock_rpc - - request = {} - await client.raw_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.raw_decrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_raw_decrypt_async(transport: str = 'grpc_asyncio', request_type=service.RawDecryptRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.raw_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.RawDecryptResponse( - plaintext=b'plaintext_blob', - protection_level=resources.ProtectionLevel.SOFTWARE, - verified_ciphertext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, - )) - response = await client.raw_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.RawDecryptRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.RawDecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.verified_ciphertext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.verified_initialization_vector_crc32c is True - - -@pytest.mark.asyncio -async def test_raw_decrypt_async_from_dict(): - await test_raw_decrypt_async(request_type=dict) - -def test_raw_decrypt_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.RawDecryptRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.raw_decrypt), - '__call__') as call: - call.return_value = service.RawDecryptResponse() - client.raw_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_raw_decrypt_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.RawDecryptRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.raw_decrypt), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.RawDecryptResponse()) - await client.raw_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'name=name_value', - ) in kw['metadata'] - - -@pytest.mark.parametrize("request_type", [ - service.AsymmetricSignRequest, - dict, -]) -def test_asymmetric_sign(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricSignResponse( - signature=b'signature_blob', - verified_digest_crc32c=True, - name='name_value', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.asymmetric_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.AsymmetricSignRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricSignResponse) - assert response.signature == b'signature_blob' - assert response.verified_digest_crc32c is True - assert response.name == 'name_value' - assert response.verified_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -def test_asymmetric_sign_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.AsymmetricSignRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.asymmetric_sign(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.AsymmetricSignRequest( - name='name_value', - ) - -def test_asymmetric_sign_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.asymmetric_sign in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.asymmetric_sign] = mock_rpc - request = {} - client.asymmetric_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.asymmetric_sign(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_asymmetric_sign_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.asymmetric_sign in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.asymmetric_sign] = mock_rpc - - request = {} - await client.asymmetric_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.asymmetric_sign(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_asymmetric_sign_async(transport: str = 'grpc_asyncio', request_type=service.AsymmetricSignRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse( - signature=b'signature_blob', - verified_digest_crc32c=True, - name='name_value', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.asymmetric_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.AsymmetricSignRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricSignResponse) - assert response.signature == b'signature_blob' - assert response.verified_digest_crc32c is True - assert response.name == 'name_value' - assert response.verified_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_asymmetric_sign_async_from_dict(): - await test_asymmetric_sign_async(request_type=dict) - -def test_asymmetric_sign_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.AsymmetricSignRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - call.return_value = service.AsymmetricSignResponse() - client.asymmetric_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_asymmetric_sign_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.AsymmetricSignRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse()) - await client.asymmetric_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_asymmetric_sign_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricSignResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.asymmetric_sign( - name='name_value', - digest=service.Digest(sha256=b'sha256_blob'), - ) - - # Establish that the 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].digest - mock_val = service.Digest(sha256=b'sha256_blob') - assert arg == mock_val - - -def test_asymmetric_sign_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.asymmetric_sign( - service.AsymmetricSignRequest(), - name='name_value', - digest=service.Digest(sha256=b'sha256_blob'), - ) - -@pytest.mark.asyncio -async def test_asymmetric_sign_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricSignResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.asymmetric_sign( - name='name_value', - digest=service.Digest(sha256=b'sha256_blob'), - ) - - # Establish that 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].digest - mock_val = service.Digest(sha256=b'sha256_blob') - assert arg == mock_val - -@pytest.mark.asyncio -async def test_asymmetric_sign_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.asymmetric_sign( - service.AsymmetricSignRequest(), - name='name_value', - digest=service.Digest(sha256=b'sha256_blob'), - ) - - -@pytest.mark.parametrize("request_type", [ - service.AsymmetricDecryptRequest, - dict, -]) -def test_asymmetric_decrypt(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricDecryptResponse( - plaintext=b'plaintext_blob', - verified_ciphertext_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.asymmetric_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.AsymmetricDecryptRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricDecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.verified_ciphertext_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -def test_asymmetric_decrypt_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.AsymmetricDecryptRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.asymmetric_decrypt(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.AsymmetricDecryptRequest( - name='name_value', - ) - -def test_asymmetric_decrypt_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.asymmetric_decrypt in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.asymmetric_decrypt] = mock_rpc - request = {} - client.asymmetric_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.asymmetric_decrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_asymmetric_decrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.asymmetric_decrypt in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.asymmetric_decrypt] = mock_rpc - - request = {} - await client.asymmetric_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.asymmetric_decrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_asymmetric_decrypt_async(transport: str = 'grpc_asyncio', request_type=service.AsymmetricDecryptRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse( - plaintext=b'plaintext_blob', - verified_ciphertext_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.asymmetric_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.AsymmetricDecryptRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricDecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.verified_ciphertext_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_asymmetric_decrypt_async_from_dict(): - await test_asymmetric_decrypt_async(request_type=dict) - -def test_asymmetric_decrypt_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.AsymmetricDecryptRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - call.return_value = service.AsymmetricDecryptResponse() - client.asymmetric_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_asymmetric_decrypt_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.AsymmetricDecryptRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse()) - await client.asymmetric_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_asymmetric_decrypt_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricDecryptResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.asymmetric_decrypt( - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - # Establish that the 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].ciphertext - mock_val = b'ciphertext_blob' - assert arg == mock_val - - -def test_asymmetric_decrypt_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.asymmetric_decrypt( - service.AsymmetricDecryptRequest(), - name='name_value', - ciphertext=b'ciphertext_blob', - ) - -@pytest.mark.asyncio -async def test_asymmetric_decrypt_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricDecryptResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.asymmetric_decrypt( - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - # Establish that 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].ciphertext - mock_val = b'ciphertext_blob' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_asymmetric_decrypt_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.asymmetric_decrypt( - service.AsymmetricDecryptRequest(), - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - -@pytest.mark.parametrize("request_type", [ - service.MacSignRequest, - dict, -]) -def test_mac_sign(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacSignResponse( - name='name_value', - mac=b'mac_blob', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.mac_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.MacSignRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.MacSignResponse) - assert response.name == 'name_value' - assert response.mac == b'mac_blob' - assert response.verified_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -def test_mac_sign_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.MacSignRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.mac_sign(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.MacSignRequest( - name='name_value', - ) - -def test_mac_sign_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.mac_sign in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.mac_sign] = mock_rpc - request = {} - client.mac_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.mac_sign(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_mac_sign_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.mac_sign in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.mac_sign] = mock_rpc - - request = {} - await client.mac_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.mac_sign(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_mac_sign_async(transport: str = 'grpc_asyncio', request_type=service.MacSignRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse( - name='name_value', - mac=b'mac_blob', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.mac_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.MacSignRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.MacSignResponse) - assert response.name == 'name_value' - assert response.mac == b'mac_blob' - assert response.verified_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_mac_sign_async_from_dict(): - await test_mac_sign_async(request_type=dict) - -def test_mac_sign_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.MacSignRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - call.return_value = service.MacSignResponse() - client.mac_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_mac_sign_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.MacSignRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse()) - await client.mac_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_mac_sign_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacSignResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.mac_sign( - name='name_value', - data=b'data_blob', - ) - - # Establish that the 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].data - mock_val = b'data_blob' - assert arg == mock_val - - -def test_mac_sign_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.mac_sign( - service.MacSignRequest(), - name='name_value', - data=b'data_blob', - ) - -@pytest.mark.asyncio -async def test_mac_sign_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacSignResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.mac_sign( - name='name_value', - data=b'data_blob', - ) - - # Establish that 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].data - mock_val = b'data_blob' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_mac_sign_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.mac_sign( - service.MacSignRequest(), - name='name_value', - data=b'data_blob', - ) - - -@pytest.mark.parametrize("request_type", [ - service.MacVerifyRequest, - dict, -]) -def test_mac_verify(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacVerifyResponse( - name='name_value', - success=True, - verified_data_crc32c=True, - verified_mac_crc32c=True, - verified_success_integrity=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.mac_verify(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.MacVerifyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.MacVerifyResponse) - assert response.name == 'name_value' - assert response.success is True - assert response.verified_data_crc32c is True - assert response.verified_mac_crc32c is True - assert response.verified_success_integrity is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -def test_mac_verify_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.MacVerifyRequest( - name='name_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.mac_verify(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.MacVerifyRequest( - name='name_value', - ) - -def test_mac_verify_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.mac_verify in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.mac_verify] = mock_rpc - request = {} - client.mac_verify(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.mac_verify(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_mac_verify_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.mac_verify in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.mac_verify] = mock_rpc - - request = {} - await client.mac_verify(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.mac_verify(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_mac_verify_async(transport: str = 'grpc_asyncio', request_type=service.MacVerifyRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse( - name='name_value', - success=True, - verified_data_crc32c=True, - verified_mac_crc32c=True, - verified_success_integrity=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - response = await client.mac_verify(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.MacVerifyRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.MacVerifyResponse) - assert response.name == 'name_value' - assert response.success is True - assert response.verified_data_crc32c is True - assert response.verified_mac_crc32c is True - assert response.verified_success_integrity is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.asyncio -async def test_mac_verify_async_from_dict(): - await test_mac_verify_async(request_type=dict) - -def test_mac_verify_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.MacVerifyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - call.return_value = service.MacVerifyResponse() - client.mac_verify(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == 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_mac_verify_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.MacVerifyRequest() - - request.name = 'name_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse()) - await client.mac_verify(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == 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_mac_verify_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacVerifyResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.mac_verify( - name='name_value', - data=b'data_blob', - mac=b'mac_blob', - ) - - # Establish that the 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].data - mock_val = b'data_blob' - assert arg == mock_val - arg = args[0].mac - mock_val = b'mac_blob' - assert arg == mock_val - - -def test_mac_verify_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.mac_verify( - service.MacVerifyRequest(), - name='name_value', - data=b'data_blob', - mac=b'mac_blob', - ) - -@pytest.mark.asyncio -async def test_mac_verify_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacVerifyResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.mac_verify( - name='name_value', - data=b'data_blob', - mac=b'mac_blob', - ) - - # Establish that 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].data - mock_val = b'data_blob' - assert arg == mock_val - arg = args[0].mac - mock_val = b'mac_blob' - assert arg == mock_val - -@pytest.mark.asyncio -async def test_mac_verify_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.mac_verify( - service.MacVerifyRequest(), - name='name_value', - data=b'data_blob', - mac=b'mac_blob', - ) - - -@pytest.mark.parametrize("request_type", [ - service.GenerateRandomBytesRequest, - dict, -]) -def test_generate_random_bytes(request_type, transport: str = 'grpc'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateRandomBytesResponse( - data=b'data_blob', - ) - response = client.generate_random_bytes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.GenerateRandomBytesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateRandomBytesResponse) - assert response.data == b'data_blob' - - -def test_generate_random_bytes_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='grpc', - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.GenerateRandomBytesRequest( - location='location_value', - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - call.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client.generate_random_bytes(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GenerateRandomBytesRequest( - location='location_value', - ) - -def test_generate_random_bytes_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_random_bytes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_random_bytes] = mock_rpc - request = {} - client.generate_random_bytes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_random_bytes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_random_bytes_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._client._transport.generate_random_bytes in client._client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.AsyncMock() - mock_rpc.return_value = mock.Mock() - client._client._transport._wrapped_methods[client._client._transport.generate_random_bytes] = mock_rpc - - request = {} - await client.generate_random_bytes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - await client.generate_random_bytes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - -@pytest.mark.asyncio -async def test_generate_random_bytes_async(transport: str = 'grpc_asyncio', request_type=service.GenerateRandomBytesRequest): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse( - data=b'data_blob', - )) - response = await client.generate_random_bytes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = service.GenerateRandomBytesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateRandomBytesResponse) - assert response.data == b'data_blob' - - -@pytest.mark.asyncio -async def test_generate_random_bytes_async_from_dict(): - await test_generate_random_bytes_async(request_type=dict) - -def test_generate_random_bytes_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GenerateRandomBytesRequest() - - request.location = 'location_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - call.return_value = service.GenerateRandomBytesResponse() - client.generate_random_bytes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'location=location_value', - ) in kw['metadata'] - - -@pytest.mark.asyncio -async def test_generate_random_bytes_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GenerateRandomBytesRequest() - - request.location = 'location_value' - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse()) - await client.generate_random_bytes(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - 'x-goog-request-params', - 'location=location_value', - ) in kw['metadata'] - - -def test_generate_random_bytes_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateRandomBytesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.generate_random_bytes( - location='location_value', - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].location - mock_val = 'location_value' - assert arg == mock_val - arg = args[0].length_bytes - mock_val = 1288 - assert arg == mock_val - arg = args[0].protection_level - mock_val = resources.ProtectionLevel.SOFTWARE - assert arg == mock_val - - -def test_generate_random_bytes_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_random_bytes( - service.GenerateRandomBytesRequest(), - location='location_value', - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - -@pytest.mark.asyncio -async def test_generate_random_bytes_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateRandomBytesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.generate_random_bytes( - location='location_value', - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].location - mock_val = 'location_value' - assert arg == mock_val - arg = args[0].length_bytes - mock_val = 1288 - assert arg == mock_val - arg = args[0].protection_level - mock_val = resources.ProtectionLevel.SOFTWARE - assert arg == mock_val - -@pytest.mark.asyncio -async def test_generate_random_bytes_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.generate_random_bytes( - service.GenerateRandomBytesRequest(), - location='location_value', - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - -def test_list_key_rings_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_key_rings in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_key_rings] = mock_rpc - - request = {} - client.list_key_rings(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_key_rings(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_key_rings_rest_required_fields(request_type=service.ListKeyRingsRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_key_rings._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_key_rings._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListKeyRingsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListKeyRingsResponse.pb(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_key_rings(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_key_rings_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_key_rings._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_key_rings_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListKeyRingsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListKeyRingsResponse.pb(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_key_rings(**mock_args) - - # Establish that the underlying call 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/*}/keyRings" % client.transport._host, args[1]) - - -def test_list_key_rings_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_key_rings( - service.ListKeyRingsRequest(), - parent='parent_value', - ) - - -def test_list_key_rings_rest_pager(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - resources.KeyRing(), - ], - next_page_token='abc', - ), - service.ListKeyRingsResponse( - key_rings=[], - next_page_token='def', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - ], - next_page_token='ghi', - ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListKeyRingsResponse.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_key_rings(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.KeyRing) - for i in results) - - pages = list(client.list_key_rings(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_crypto_keys_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_crypto_keys in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_crypto_keys] = mock_rpc - - request = {} - client.list_crypto_keys(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_crypto_keys(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_crypto_keys_rest_required_fields(request_type=service.ListCryptoKeysRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_crypto_keys._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_crypto_keys._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", "version_view", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListCryptoKeysResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListCryptoKeysResponse.pb(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_crypto_keys(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_crypto_keys_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_crypto_keys._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", "versionView", )) & set(("parent", ))) - - -def test_list_crypto_keys_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListCryptoKeysResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListCryptoKeysResponse.pb(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_crypto_keys(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate("%s/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys" % client.transport._host, args[1]) - - -def test_list_crypto_keys_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_crypto_keys( - service.ListCryptoKeysRequest(), - parent='parent_value', - ) - - -def test_list_crypto_keys_rest_pager(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - resources.CryptoKey(), - ], - next_page_token='abc', - ), - service.ListCryptoKeysResponse( - crypto_keys=[], - next_page_token='def', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListCryptoKeysResponse.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/keyRings/sample3'} - - pager = client.list_crypto_keys(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.CryptoKey) - for i in results) - - pages = list(client.list_crypto_keys(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_crypto_key_versions_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_crypto_key_versions in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_crypto_key_versions] = mock_rpc - - request = {} - client.list_crypto_key_versions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_crypto_key_versions(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_crypto_key_versions_rest_required_fields(request_type=service.ListCryptoKeyVersionsRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_crypto_key_versions._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_crypto_key_versions._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", "view", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListCryptoKeyVersionsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListCryptoKeyVersionsResponse.pb(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_crypto_key_versions(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_crypto_key_versions_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_crypto_key_versions._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", "view", )) & set(("parent", ))) - - -def test_list_crypto_key_versions_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListCryptoKeyVersionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListCryptoKeyVersionsResponse.pb(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_crypto_key_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/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions" % client.transport._host, args[1]) - - -def test_list_crypto_key_versions_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_crypto_key_versions( - service.ListCryptoKeyVersionsRequest(), - parent='parent_value', - ) - - -def test_list_crypto_key_versions_rest_pager(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - next_page_token='abc', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[], - next_page_token='def', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - ], - next_page_token='ghi', - ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListCryptoKeyVersionsResponse.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/keyRings/sample3/cryptoKeys/sample4'} - - pager = client.list_crypto_key_versions(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.CryptoKeyVersion) - for i in results) - - pages = list(client.list_crypto_key_versions(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_list_import_jobs_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.list_import_jobs in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.list_import_jobs] = mock_rpc - - request = {} - client.list_import_jobs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_import_jobs(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_list_import_jobs_rest_required_fields(request_type=service.ListImportJobsRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_import_jobs._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).list_import_jobs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("filter", "order_by", "page_size", "page_token", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.ListImportJobsResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListImportJobsResponse.pb(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_import_jobs(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_list_import_jobs_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.list_import_jobs._get_unset_required_fields({}) - assert set(unset_fields) == (set(("filter", "orderBy", "pageSize", "pageToken", )) & set(("parent", ))) - - -def test_list_import_jobs_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListImportJobsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.ListImportJobsResponse.pb(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_import_jobs(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*}/importJobs" % client.transport._host, args[1]) - - -def test_list_import_jobs_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_import_jobs( - service.ListImportJobsRequest(), - parent='parent_value', - ) - - -def test_list_import_jobs_rest_pager(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - #with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - resources.ImportJob(), - ], - next_page_token='abc', - ), - service.ListImportJobsResponse( - import_jobs=[], - next_page_token='def', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - ], - next_page_token='ghi', - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListImportJobsResponse.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/keyRings/sample3'} - - pager = client.list_import_jobs(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.ImportJob) - for i in results) - - pages = list(client.list_import_jobs(request=sample_request).pages) - for page_, token in zip(pages, ['abc','def','ghi', '']): - assert page_.raw_page.next_page_token == token - - -def test_get_key_ring_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_key_ring in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_key_ring] = mock_rpc - - request = {} - client.get_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_key_ring(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_key_ring_rest_required_fields(request_type=service.GetKeyRingRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_key_ring._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_key_ring._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.KeyRing() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.KeyRing.pb(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_key_ring(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_key_ring_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_key_ring._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_key_ring_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.KeyRing() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.KeyRing.pb(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_key_ring(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*}" % client.transport._host, args[1]) - - -def test_get_key_ring_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_key_ring( - service.GetKeyRingRequest(), - name='name_value', - ) - - -def test_get_crypto_key_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_crypto_key in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_crypto_key] = mock_rpc - - request = {} - client.get_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_crypto_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_crypto_key_rest_required_fields(request_type=service.GetCryptoKeyRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_crypto_key._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_crypto_key._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(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_crypto_key(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_crypto_key_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_crypto_key._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_crypto_key_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(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_crypto_key(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*}" % client.transport._host, args[1]) - - -def test_get_crypto_key_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_crypto_key( - service.GetCryptoKeyRequest(), - name='name_value', - ) - - -def test_get_crypto_key_version_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_crypto_key_version] = mock_rpc - - request = {} - client.get_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_crypto_key_version_rest_required_fields(request_type=service.GetCryptoKeyVersionRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_crypto_key_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_crypto_key_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(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_crypto_key_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_crypto_key_version_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_crypto_key_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_crypto_key_version_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(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_crypto_key_version(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}" % client.transport._host, args[1]) - - -def test_get_crypto_key_version_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_crypto_key_version( - service.GetCryptoKeyVersionRequest(), - name='name_value', - ) - - -def test_get_public_key_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_public_key in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_public_key] = mock_rpc - - request = {} - client.get_public_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_public_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_public_key_rest_required_fields(request_type=service.GetPublicKeyRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_public_key._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_public_key._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.PublicKey() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.PublicKey.pb(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_public_key(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_public_key_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_public_key._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_public_key_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.PublicKey() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.PublicKey.pb(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_public_key(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}/publicKey" % client.transport._host, args[1]) - - -def test_get_public_key_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_public_key( - service.GetPublicKeyRequest(), - name='name_value', - ) - - -def test_get_import_job_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.get_import_job in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.get_import_job] = mock_rpc - - request = {} - client.get_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_import_job(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_get_import_job_rest_required_fields(request_type=service.GetImportJobRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_import_job._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).get_import_job._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.ImportJob() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "get", - 'query_params': pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.ImportJob.pb(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_import_job(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_get_import_job_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.get_import_job._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_get_import_job_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.ImportJob() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/importJobs/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.ImportJob.pb(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_import_job(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/importJobs/*}" % client.transport._host, args[1]) - - -def test_get_import_job_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_import_job( - service.GetImportJobRequest(), - name='name_value', - ) - - -def test_create_key_ring_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_key_ring in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_key_ring] = mock_rpc - - request = {} - client.create_key_ring(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_key_ring(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_key_ring_rest_required_fields(request_type=service.CreateKeyRingRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["key_ring_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "keyRingId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_key_ring._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "keyRingId" in jsonified_request - assert jsonified_request["keyRingId"] == request_init["key_ring_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["keyRingId"] = 'key_ring_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_key_ring._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("key_ring_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "keyRingId" in jsonified_request - assert jsonified_request["keyRingId"] == 'key_ring_id_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.KeyRing() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.KeyRing.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_key_ring(request) - - expected_params = [ - ( - "keyRingId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_key_ring_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_key_ring._get_unset_required_fields({}) - assert set(unset_fields) == (set(("keyRingId", )) & set(("parent", "keyRingId", "keyRing", ))) - - -def test_create_key_ring_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.KeyRing() - - # 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', - key_ring_id='key_ring_id_value', - key_ring=resources.KeyRing(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.KeyRing.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_key_ring(**mock_args) - - # Establish that the underlying call 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/*}/keyRings" % client.transport._host, args[1]) - - -def test_create_key_ring_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_key_ring( - service.CreateKeyRingRequest(), - parent='parent_value', - key_ring_id='key_ring_id_value', - key_ring=resources.KeyRing(name='name_value'), - ) - - -def test_create_crypto_key_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_crypto_key in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_crypto_key] = mock_rpc - - request = {} - client.create_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_crypto_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_crypto_key_rest_required_fields(request_type=service.CreateCryptoKeyRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["crypto_key_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "cryptoKeyId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_crypto_key._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "cryptoKeyId" in jsonified_request - assert jsonified_request["cryptoKeyId"] == request_init["crypto_key_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["cryptoKeyId"] = 'crypto_key_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_crypto_key._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("crypto_key_id", "skip_initial_version_creation", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "cryptoKeyId" in jsonified_request - assert jsonified_request["cryptoKeyId"] == 'crypto_key_id_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_crypto_key(request) - - expected_params = [ - ( - "cryptoKeyId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_crypto_key_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_crypto_key._get_unset_required_fields({}) - assert set(unset_fields) == (set(("cryptoKeyId", "skipInitialVersionCreation", )) & set(("parent", "cryptoKeyId", "cryptoKey", ))) - - -def test_create_crypto_key_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - crypto_key_id='crypto_key_id_value', - crypto_key=resources.CryptoKey(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_crypto_key(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*}/cryptoKeys" % client.transport._host, args[1]) - - -def test_create_crypto_key_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_crypto_key( - service.CreateCryptoKeyRequest(), - parent='parent_value', - crypto_key_id='crypto_key_id_value', - crypto_key=resources.CryptoKey(name='name_value'), - ) - - -def test_create_crypto_key_version_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_crypto_key_version] = mock_rpc - - request = {} - client.create_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_crypto_key_version_rest_required_fields(request_type=service.CreateCryptoKeyVersionRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_crypto_key_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_crypto_key_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_crypto_key_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_crypto_key_version_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_crypto_key_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "cryptoKeyVersion", ))) - - -def test_create_crypto_key_version_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - crypto_key_version=resources.CryptoKeyVersion(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_crypto_key_version(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions" % client.transport._host, args[1]) - - -def test_create_crypto_key_version_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_crypto_key_version( - service.CreateCryptoKeyVersionRequest(), - parent='parent_value', - crypto_key_version=resources.CryptoKeyVersion(name='name_value'), - ) - - -def test_import_crypto_key_version_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.import_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.import_crypto_key_version] = mock_rpc - - request = {} - client.import_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.import_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_import_crypto_key_version_rest_required_fields(request_type=service.ImportCryptoKeyVersionRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["import_job"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_crypto_key_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = 'parent_value' - jsonified_request["importJob"] = 'import_job_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).import_crypto_key_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "importJob" in jsonified_request - assert jsonified_request["importJob"] == 'import_job_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(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.import_crypto_key_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_import_crypto_key_version_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.import_crypto_key_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("parent", "algorithm", "importJob", ))) - - -def test_create_import_job_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.create_import_job in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.create_import_job] = mock_rpc - - request = {} - client.create_import_job(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.create_import_job(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_create_import_job_rest_required_fields(request_type=service.CreateImportJobRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["import_job_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - assert "importJobId" not in jsonified_request - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_import_job._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "importJobId" in jsonified_request - assert jsonified_request["importJobId"] == request_init["import_job_id"] - - jsonified_request["parent"] = 'parent_value' - jsonified_request["importJobId"] = 'import_job_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).create_import_job._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("import_job_id", )) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == 'parent_value' - assert "importJobId" in jsonified_request - assert jsonified_request["importJobId"] == 'import_job_id_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.ImportJob() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.ImportJob.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.create_import_job(request) - - expected_params = [ - ( - "importJobId", - "", - ), - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_create_import_job_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.create_import_job._get_unset_required_fields({}) - assert set(unset_fields) == (set(("importJobId", )) & set(("parent", "importJobId", "importJob", ))) - - -def test_create_import_job_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.ImportJob() - - # get arguments that satisfy an http rule for this method - sample_request = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - - # get truthy value for each flattened field - mock_args = dict( - parent='parent_value', - import_job_id='import_job_id_value', - import_job=resources.ImportJob(name='name_value'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.ImportJob.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.create_import_job(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*}/importJobs" % client.transport._host, args[1]) - - -def test_create_import_job_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_import_job( - service.CreateImportJobRequest(), - parent='parent_value', - import_job_id='import_job_id_value', - import_job=resources.ImportJob(name='name_value'), - ) - - -def test_update_crypto_key_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_crypto_key in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_crypto_key] = mock_rpc - - request = {} - client.update_crypto_key(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_crypto_key(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_crypto_key_rest_required_fields(request_type=service.UpdateCryptoKeyRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_crypto_key._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_crypto_key._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 = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() - # 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 - - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_crypto_key(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_crypto_key_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_crypto_key._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("cryptoKey", "updateMask", ))) - - -def test_update_crypto_key_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() - - # get arguments that satisfy an http rule for this method - sample_request = {'crypto_key': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'}} - - # get truthy value for each flattened field - mock_args = dict( - crypto_key=resources.CryptoKey(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 - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_crypto_key(**mock_args) - - # Establish that the underlying call 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/{crypto_key.name=projects/*/locations/*/keyRings/*/cryptoKeys/*}" % client.transport._host, args[1]) - - -def test_update_crypto_key_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_crypto_key( - service.UpdateCryptoKeyRequest(), - crypto_key=resources.CryptoKey(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_crypto_key_version_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_crypto_key_version] = mock_rpc - - request = {} - client.update_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_crypto_key_version_rest_required_fields(request_type=service.UpdateCryptoKeyVersionRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_crypto_key_version._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_crypto_key_version._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 = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() - # 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 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_crypto_key_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_crypto_key_version_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_crypto_key_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(("updateMask", )) & set(("cryptoKeyVersion", "updateMask", ))) - - -def test_update_crypto_key_version_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'crypto_key_version': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'}} - - # get truthy value for each flattened field - mock_args = dict( - crypto_key_version=resources.CryptoKeyVersion(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 - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_crypto_key_version(**mock_args) - - # Establish that the underlying call 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/{crypto_key_version.name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}" % client.transport._host, args[1]) - - -def test_update_crypto_key_version_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_crypto_key_version( - service.UpdateCryptoKeyVersionRequest(), - crypto_key_version=resources.CryptoKeyVersion(name='name_value'), - update_mask=field_mask_pb2.FieldMask(paths=['paths_value']), - ) - - -def test_update_crypto_key_primary_version_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.update_crypto_key_primary_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.update_crypto_key_primary_version] = mock_rpc - - request = {} - client.update_crypto_key_primary_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.update_crypto_key_primary_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_update_crypto_key_primary_version_rest_required_fields(request_type=service.UpdateCryptoKeyPrimaryVersionRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["crypto_key_version_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_crypto_key_primary_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["cryptoKeyVersionId"] = 'crypto_key_version_id_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).update_crypto_key_primary_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "cryptoKeyVersionId" in jsonified_request - assert jsonified_request["cryptoKeyVersionId"] == 'crypto_key_version_id_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - response = client.update_crypto_key_primary_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_update_crypto_key_primary_version_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.update_crypto_key_primary_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "cryptoKeyVersionId", ))) - - -def test_update_crypto_key_primary_version_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - crypto_key_version_id='crypto_key_version_id_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode('UTF-8') - req.return_value = response_value - - client.update_crypto_key_primary_version(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*}:updatePrimaryVersion" % client.transport._host, args[1]) - - -def test_update_crypto_key_primary_version_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.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_crypto_key_primary_version( - service.UpdateCryptoKeyPrimaryVersionRequest(), - name='name_value', - crypto_key_version_id='crypto_key_version_id_value', - ) - - -def test_destroy_crypto_key_version_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.destroy_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.destroy_crypto_key_version] = mock_rpc - - request = {} - client.destroy_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.destroy_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_destroy_crypto_key_version_rest_required_fields(request_type=service.DestroyCryptoKeyVersionRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).destroy_crypto_key_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).destroy_crypto_key_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(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.destroy_crypto_key_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_destroy_crypto_key_version_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.destroy_crypto_key_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_destroy_crypto_key_version_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(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.destroy_crypto_key_version(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:destroy" % client.transport._host, args[1]) - - -def test_destroy_crypto_key_version_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.destroy_crypto_key_version( - service.DestroyCryptoKeyVersionRequest(), - name='name_value', - ) - - -def test_restore_crypto_key_version_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.restore_crypto_key_version in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.restore_crypto_key_version] = mock_rpc - - request = {} - client.restore_crypto_key_version(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.restore_crypto_key_version(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_restore_crypto_key_version_rest_required_fields(request_type=service.RestoreCryptoKeyVersionRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_crypto_key_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).restore_crypto_key_version._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(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.restore_crypto_key_version(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_restore_crypto_key_version_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.restore_crypto_key_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_restore_crypto_key_version_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(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.restore_crypto_key_version(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:restore" % client.transport._host, args[1]) - - -def test_restore_crypto_key_version_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.restore_crypto_key_version( - service.RestoreCryptoKeyVersionRequest(), - name='name_value', - ) - - -def test_encrypt_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.encrypt in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.encrypt] = mock_rpc - - request = {} - client.encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.encrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_encrypt_rest_required_fields(request_type=service.EncryptRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["plaintext"] = b'' - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).encrypt._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["plaintext"] = b'plaintext_blob' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).encrypt._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "plaintext" in jsonified_request - assert jsonified_request["plaintext"] == b'plaintext_blob' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.EncryptResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.EncryptResponse.pb(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.encrypt(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_encrypt_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.encrypt._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "plaintext", ))) - - -def test_encrypt_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.EncryptResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - plaintext=b'plaintext_blob', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.EncryptResponse.pb(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.encrypt(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/**}:encrypt" % client.transport._host, args[1]) - - -def test_encrypt_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.encrypt( - service.EncryptRequest(), - name='name_value', - plaintext=b'plaintext_blob', - ) - - -def test_decrypt_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.decrypt in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.decrypt] = mock_rpc - - request = {} - client.decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.decrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_decrypt_rest_required_fields(request_type=service.DecryptRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["ciphertext"] = b'' - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).decrypt._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["ciphertext"] = b'ciphertext_blob' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).decrypt._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "ciphertext" in jsonified_request - assert jsonified_request["ciphertext"] == b'ciphertext_blob' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.DecryptResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.DecryptResponse.pb(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.decrypt(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_decrypt_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.decrypt._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "ciphertext", ))) - - -def test_decrypt_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.DecryptResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ciphertext=b'ciphertext_blob', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.DecryptResponse.pb(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.decrypt(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*}:decrypt" % client.transport._host, args[1]) - - -def test_decrypt_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.decrypt( - service.DecryptRequest(), - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - -def test_raw_encrypt_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.raw_encrypt in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.raw_encrypt] = mock_rpc - - request = {} - client.raw_encrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.raw_encrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_raw_encrypt_rest_required_fields(request_type=service.RawEncryptRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["plaintext"] = b'' - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).raw_encrypt._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["plaintext"] = b'plaintext_blob' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).raw_encrypt._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "plaintext" in jsonified_request - assert jsonified_request["plaintext"] == b'plaintext_blob' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.RawEncryptResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.RawEncryptResponse.pb(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.raw_encrypt(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_raw_encrypt_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.raw_encrypt._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "plaintext", ))) - - -def test_raw_decrypt_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.raw_decrypt in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.raw_decrypt] = mock_rpc - - request = {} - client.raw_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.raw_decrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_raw_decrypt_rest_required_fields(request_type=service.RawDecryptRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["ciphertext"] = b'' - request_init["initialization_vector"] = b'' - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).raw_decrypt._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["ciphertext"] = b'ciphertext_blob' - jsonified_request["initializationVector"] = b'initialization_vector_blob' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).raw_decrypt._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "ciphertext" in jsonified_request - assert jsonified_request["ciphertext"] == b'ciphertext_blob' - assert "initializationVector" in jsonified_request - assert jsonified_request["initializationVector"] == b'initialization_vector_blob' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.RawDecryptResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.RawDecryptResponse.pb(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.raw_decrypt(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_raw_decrypt_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.raw_decrypt._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "ciphertext", "initializationVector", ))) - - -def test_asymmetric_sign_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.asymmetric_sign in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.asymmetric_sign] = mock_rpc - - request = {} - client.asymmetric_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.asymmetric_sign(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_asymmetric_sign_rest_required_fields(request_type=service.AsymmetricSignRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).asymmetric_sign._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).asymmetric_sign._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.AsymmetricSignResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.AsymmetricSignResponse.pb(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.asymmetric_sign(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_asymmetric_sign_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.asymmetric_sign._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", ))) - - -def test_asymmetric_sign_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.AsymmetricSignResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - digest=service.Digest(sha256=b'sha256_blob'), - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.AsymmetricSignResponse.pb(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.asymmetric_sign(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricSign" % client.transport._host, args[1]) - - -def test_asymmetric_sign_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.asymmetric_sign( - service.AsymmetricSignRequest(), - name='name_value', - digest=service.Digest(sha256=b'sha256_blob'), - ) - - -def test_asymmetric_decrypt_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.asymmetric_decrypt in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.asymmetric_decrypt] = mock_rpc - - request = {} - client.asymmetric_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.asymmetric_decrypt(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_asymmetric_decrypt_rest_required_fields(request_type=service.AsymmetricDecryptRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["ciphertext"] = b'' - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).asymmetric_decrypt._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["ciphertext"] = b'ciphertext_blob' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).asymmetric_decrypt._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "ciphertext" in jsonified_request - assert jsonified_request["ciphertext"] == b'ciphertext_blob' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.AsymmetricDecryptResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.AsymmetricDecryptResponse.pb(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.asymmetric_decrypt(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_asymmetric_decrypt_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.asymmetric_decrypt._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "ciphertext", ))) - - -def test_asymmetric_decrypt_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.AsymmetricDecryptResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - ciphertext=b'ciphertext_blob', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.AsymmetricDecryptResponse.pb(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.asymmetric_decrypt(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:asymmetricDecrypt" % client.transport._host, args[1]) - - -def test_asymmetric_decrypt_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.asymmetric_decrypt( - service.AsymmetricDecryptRequest(), - name='name_value', - ciphertext=b'ciphertext_blob', - ) - - -def test_mac_sign_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.mac_sign in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.mac_sign] = mock_rpc - - request = {} - client.mac_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.mac_sign(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_mac_sign_rest_required_fields(request_type=service.MacSignRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["data"] = b'' - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).mac_sign._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["data"] = b'data_blob' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).mac_sign._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "data" in jsonified_request - assert jsonified_request["data"] == b'data_blob' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.MacSignResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.MacSignResponse.pb(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.mac_sign(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_mac_sign_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.mac_sign._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "data", ))) - - -def test_mac_sign_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.MacSignResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - data=b'data_blob', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.MacSignResponse.pb(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.mac_sign(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macSign" % client.transport._host, args[1]) - - -def test_mac_sign_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.mac_sign( - service.MacSignRequest(), - name='name_value', - data=b'data_blob', - ) - - -def test_mac_verify_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.mac_verify in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.mac_verify] = mock_rpc - - request = {} - client.mac_verify(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.mac_verify(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_mac_verify_rest_required_fields(request_type=service.MacVerifyRequest): - transport_class = transports.KeyManagementServiceRestTransport - - request_init = {} - request_init["name"] = "" - request_init["data"] = b'' - request_init["mac"] = b'' - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads(json_format.MessageToJson( - pb_request, - use_integers_for_enums=False - )) - - # verify fields with default values are dropped - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).mac_verify._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = 'name_value' - jsonified_request["data"] = b'data_blob' - jsonified_request["mac"] = b'mac_blob' - - unset_fields = transport_class(credentials=ga_credentials.AnonymousCredentials()).mac_verify._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == 'name_value' - assert "data" in jsonified_request - assert jsonified_request["data"] == b'data_blob' - assert "mac" in jsonified_request - assert jsonified_request["mac"] == b'mac_blob' - - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport='rest', - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = service.MacVerifyResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, 'transcode') as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - 'uri': 'v1/sample_method', - 'method': "post", - 'query_params': pb_request, - } - transcode_result['body'] = pb_request - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.MacVerifyResponse.pb(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.mac_verify(request) - - expected_params = [ - ('$alt', 'json;enum-encoding=int') - ] - actual_params = req.call_args.kwargs['params'] - assert expected_params == actual_params - - -def test_mac_verify_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport(credentials=ga_credentials.AnonymousCredentials) - - unset_fields = transport.mac_verify._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name", "data", "mac", ))) - - -def test_mac_verify_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.MacVerifyResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - - # get truthy value for each flattened field - mock_args = dict( - name='name_value', - data=b'data_blob', - mac=b'mac_blob', - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.MacVerifyResponse.pb(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.mac_verify(**mock_args) - - # Establish that the underlying call 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/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:macVerify" % client.transport._host, args[1]) - - -def test_mac_verify_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.mac_verify( - service.MacVerifyRequest(), - name='name_value', - data=b'data_blob', - mac=b'mac_blob', - ) - - -def test_generate_random_bytes_rest_use_cached_wrapped_rpc(): - # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, - # instead of constructing them on each call - with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() - - # Ensure method has been cached - assert client._transport.generate_random_bytes in client._transport._wrapped_methods - - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = "foo" # operation_request.operation in compute client(s) expect a string. - client._transport._wrapped_methods[client._transport.generate_random_bytes] = mock_rpc - - request = {} - client.generate_random_bytes(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.generate_random_bytes(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 - - -def test_generate_random_bytes_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.GenerateRandomBytesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {'location': 'projects/sample1/locations/sample2'} - - # get truthy value for each flattened field - mock_args = dict( - location='location_value', - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = service.GenerateRandomBytesResponse.pb(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.generate_random_bytes(**mock_args) - - # Establish that the underlying call 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/{location=projects/*/locations/*}:generateRandomBytes" % client.transport._host, args[1]) - - -def test_generate_random_bytes_rest_flattened_error(transport: str = 'rest'): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.generate_random_bytes( - service.GenerateRandomBytesRequest(), - location='location_value', - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.KeyManagementServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.KeyManagementServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide an api_key and a transport instance. - transport = transports.KeyManagementServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - client_options=options, - transport=transport, - ) - - # It is an error to provide an api_key and a credential. - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - client_options=options, - credentials=ga_credentials.AnonymousCredentials() - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.KeyManagementServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = KeyManagementServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.KeyManagementServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = KeyManagementServiceClient(transport=transport) - assert client.transport is transport - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.KeyManagementServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.KeyManagementServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - -@pytest.mark.parametrize("transport_class", [ - transports.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceGrpcAsyncIOTransport, - transports.KeyManagementServiceRestTransport, -]) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - -def test_transport_kind_grpc(): - transport = KeyManagementServiceClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_key_rings_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - call.return_value = service.ListKeyRingsResponse() - client.list_key_rings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListKeyRingsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_crypto_keys_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - call.return_value = service.ListCryptoKeysResponse() - client.list_crypto_keys(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListCryptoKeysRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_crypto_key_versions_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - call.return_value = service.ListCryptoKeyVersionsResponse() - client.list_crypto_key_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListCryptoKeyVersionsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_import_jobs_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - call.return_value = service.ListImportJobsResponse() - client.list_import_jobs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListImportJobsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_key_ring_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - call.return_value = resources.KeyRing() - client.get_key_ring(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetKeyRingRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_crypto_key_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.get_crypto_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetCryptoKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_crypto_key_version_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.get_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_public_key_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - call.return_value = resources.PublicKey() - client.get_public_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetPublicKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_import_job_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - call.return_value = resources.ImportJob() - client.get_import_job(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetImportJobRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_key_ring_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - call.return_value = resources.KeyRing() - client.create_key_ring(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateKeyRingRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_crypto_key_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.create_crypto_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateCryptoKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_crypto_key_version_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.create_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_import_crypto_key_version_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.import_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ImportCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_import_job_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - call.return_value = resources.ImportJob() - client.create_import_job(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateImportJobRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_crypto_key_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.update_crypto_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_crypto_key_version_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.update_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_crypto_key_primary_version_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - call.return_value = resources.CryptoKey() - client.update_crypto_key_primary_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyPrimaryVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_destroy_crypto_key_version_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.destroy_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DestroyCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_restore_crypto_key_version_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - call.return_value = resources.CryptoKeyVersion() - client.restore_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.RestoreCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_encrypt_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - call.return_value = service.EncryptResponse() - client.encrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.EncryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_decrypt_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - call.return_value = service.DecryptResponse() - client.decrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DecryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_raw_encrypt_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.raw_encrypt), - '__call__') as call: - call.return_value = service.RawEncryptResponse() - client.raw_encrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.RawEncryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_raw_decrypt_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.raw_decrypt), - '__call__') as call: - call.return_value = service.RawDecryptResponse() - client.raw_decrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.RawDecryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_asymmetric_sign_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - call.return_value = service.AsymmetricSignResponse() - client.asymmetric_sign(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.AsymmetricSignRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_asymmetric_decrypt_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - call.return_value = service.AsymmetricDecryptResponse() - client.asymmetric_decrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.AsymmetricDecryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_mac_sign_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - call.return_value = service.MacSignResponse() - client.mac_sign(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.MacSignRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_mac_verify_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - call.return_value = service.MacVerifyResponse() - client.mac_verify(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.MacVerifyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_random_bytes_empty_call_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - call.return_value = service.GenerateRandomBytesResponse() - client.generate_random_bytes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GenerateRandomBytesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = KeyManagementServiceAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" - - -def test_initialize_client_w_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_key_rings_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListKeyRingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_key_rings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListKeyRingsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_crypto_keys_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeysResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_crypto_keys(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListCryptoKeysRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_crypto_key_versions_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListCryptoKeyVersionsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_crypto_key_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListCryptoKeyVersionsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_list_import_jobs_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.ListImportJobsResponse( - next_page_token='next_page_token_value', - total_size=1086, - )) - await client.list_import_jobs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListImportJobsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_key_ring_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( - name='name_value', - )) - await client.get_key_ring(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetKeyRingRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_crypto_key_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - )) - await client.get_crypto_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetCryptoKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_crypto_key_version_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - await client.get_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_public_key_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.PublicKey( - pem='pem_value', - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - name='name_value', - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - await client.get_public_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetPublicKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_import_job_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - )) - await client.get_import_job(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetImportJobRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_key_ring_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.KeyRing( - name='name_value', - )) - await client.create_key_ring(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateKeyRingRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_crypto_key_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - )) - await client.create_crypto_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateCryptoKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_crypto_key_version_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - await client.create_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_import_crypto_key_version_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - await client.import_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ImportCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_create_import_job_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - )) - await client.create_import_job(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateImportJobRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_crypto_key_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - )) - await client.update_crypto_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_crypto_key_version_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - await client.update_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_crypto_key_primary_version_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - )) - await client.update_crypto_key_primary_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyPrimaryVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_destroy_crypto_key_version_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - await client.destroy_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DestroyCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_restore_crypto_key_version_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - )) - await client.restore_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.RestoreCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_encrypt_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.EncryptResponse( - name='name_value', - ciphertext=b'ciphertext_blob', - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - await client.encrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.EncryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_decrypt_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.DecryptResponse( - plaintext=b'plaintext_blob', - used_primary=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - await client.decrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DecryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_raw_encrypt_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.raw_encrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.RawEncryptResponse( - ciphertext=b'ciphertext_blob', - initialization_vector=b'initialization_vector_blob', - tag_length=1053, - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, - name='name_value', - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - await client.raw_encrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.RawEncryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_raw_decrypt_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.raw_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.RawDecryptResponse( - plaintext=b'plaintext_blob', - protection_level=resources.ProtectionLevel.SOFTWARE, - verified_ciphertext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, - )) - await client.raw_decrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.RawDecryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_asymmetric_sign_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricSignResponse( - signature=b'signature_blob', - verified_digest_crc32c=True, - name='name_value', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - await client.asymmetric_sign(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.AsymmetricSignRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_asymmetric_decrypt_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.AsymmetricDecryptResponse( - plaintext=b'plaintext_blob', - verified_ciphertext_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - await client.asymmetric_decrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.AsymmetricDecryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_mac_sign_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacSignResponse( - name='name_value', - mac=b'mac_blob', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - await client.mac_sign(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.MacSignRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_mac_verify_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.MacVerifyResponse( - name='name_value', - success=True, - verified_data_crc32c=True, - verified_mac_crc32c=True, - verified_success_integrity=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - )) - await client.mac_verify(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.MacVerifyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_generate_random_bytes_empty_call_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.GenerateRandomBytesResponse( - data=b'data_blob', - )) - await client.generate_random_bytes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GenerateRandomBytesRequest() - - assert args[0] == request_msg - - -def test_transport_kind_rest(): - transport = KeyManagementServiceClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" - - -def test_list_key_rings_rest_bad_request(request_type=service.ListKeyRingsRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_key_rings(request) - - -@pytest.mark.parametrize("request_type", [ - service.ListKeyRingsRequest, - dict, -]) -def test_list_key_rings_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListKeyRingsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListKeyRingsResponse.pb(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_key_rings(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListKeyRingsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_key_rings_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_list_key_rings") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_list_key_rings") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListKeyRingsRequest.pb(service.ListKeyRingsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.ListKeyRingsResponse.to_json(service.ListKeyRingsResponse()) - req.return_value.content = return_value - - request = service.ListKeyRingsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListKeyRingsResponse() - - client.list_key_rings(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_crypto_keys_rest_bad_request(request_type=service.ListCryptoKeysRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_crypto_keys(request) - - -@pytest.mark.parametrize("request_type", [ - service.ListCryptoKeysRequest, - dict, -]) -def test_list_crypto_keys_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListCryptoKeysResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListCryptoKeysResponse.pb(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_crypto_keys(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCryptoKeysPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_crypto_keys_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_list_crypto_keys") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_list_crypto_keys") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListCryptoKeysRequest.pb(service.ListCryptoKeysRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.ListCryptoKeysResponse.to_json(service.ListCryptoKeysResponse()) - req.return_value.content = return_value - - request = service.ListCryptoKeysRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListCryptoKeysResponse() - - client.list_crypto_keys(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_crypto_key_versions_rest_bad_request(request_type=service.ListCryptoKeyVersionsRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_crypto_key_versions(request) - - -@pytest.mark.parametrize("request_type", [ - service.ListCryptoKeyVersionsRequest, - dict, -]) -def test_list_crypto_key_versions_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListCryptoKeyVersionsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListCryptoKeyVersionsResponse.pb(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_crypto_key_versions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListCryptoKeyVersionsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_crypto_key_versions_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_list_crypto_key_versions") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_list_crypto_key_versions") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListCryptoKeyVersionsRequest.pb(service.ListCryptoKeyVersionsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.ListCryptoKeyVersionsResponse.to_json(service.ListCryptoKeyVersionsResponse()) - req.return_value.content = return_value - - request = service.ListCryptoKeyVersionsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListCryptoKeyVersionsResponse() - - client.list_crypto_key_versions(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_list_import_jobs_rest_bad_request(request_type=service.ListImportJobsRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.list_import_jobs(request) - - -@pytest.mark.parametrize("request_type", [ - service.ListImportJobsRequest, - dict, -]) -def test_list_import_jobs_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.ListImportJobsResponse( - next_page_token='next_page_token_value', - total_size=1086, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.ListImportJobsResponse.pb(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_import_jobs(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListImportJobsPager) - assert response.next_page_token == 'next_page_token_value' - assert response.total_size == 1086 - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_import_jobs_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_list_import_jobs") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_list_import_jobs") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ListImportJobsRequest.pb(service.ListImportJobsRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.ListImportJobsResponse.to_json(service.ListImportJobsResponse()) - req.return_value.content = return_value - - request = service.ListImportJobsRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.ListImportJobsResponse() - - client.list_import_jobs(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_key_ring_rest_bad_request(request_type=service.GetKeyRingRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_key_ring(request) - - -@pytest.mark.parametrize("request_type", [ - service.GetKeyRingRequest, - dict, -]) -def test_get_key_ring_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.KeyRing( - name='name_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.KeyRing.pb(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_key_ring(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.KeyRing) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_key_ring_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_get_key_ring") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_get_key_ring") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetKeyRingRequest.pb(service.GetKeyRingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.KeyRing.to_json(resources.KeyRing()) - req.return_value.content = return_value - - request = service.GetKeyRingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.KeyRing() - - client.get_key_ring(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_crypto_key_rest_bad_request(request_type=service.GetCryptoKeyRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_crypto_key(request) - - -@pytest.mark.parametrize("request_type", [ - service.GetCryptoKeyRequest, - dict, -]) -def test_get_crypto_key_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(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_crypto_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_crypto_key_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_get_crypto_key") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_get_crypto_key") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetCryptoKeyRequest.pb(service.GetCryptoKeyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.CryptoKey.to_json(resources.CryptoKey()) - req.return_value.content = return_value - - request = service.GetCryptoKeyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CryptoKey() - - client.get_crypto_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_crypto_key_version_rest_bad_request(request_type=service.GetCryptoKeyVersionRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_crypto_key_version(request) - - -@pytest.mark.parametrize("request_type", [ - service.GetCryptoKeyVersionRequest, - dict, -]) -def test_get_crypto_key_version_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(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_crypto_key_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_crypto_key_version_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_get_crypto_key_version") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_get_crypto_key_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetCryptoKeyVersionRequest.pb(service.GetCryptoKeyVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) - req.return_value.content = return_value - - request = service.GetCryptoKeyVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CryptoKeyVersion() - - client.get_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_public_key_rest_bad_request(request_type=service.GetPublicKeyRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_public_key(request) - - -@pytest.mark.parametrize("request_type", [ - service.GetPublicKeyRequest, - dict, -]) -def test_get_public_key_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.PublicKey( - pem='pem_value', - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - name='name_value', - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.PublicKey.pb(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_public_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.PublicKey) - assert response.pem == 'pem_value' - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.name == 'name_value' - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_public_key_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_get_public_key") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_get_public_key") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetPublicKeyRequest.pb(service.GetPublicKeyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.PublicKey.to_json(resources.PublicKey()) - req.return_value.content = return_value - - request = service.GetPublicKeyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.PublicKey() - - client.get_public_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_import_job_rest_bad_request(request_type=service.GetImportJobRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/importJobs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.get_import_job(request) - - -@pytest.mark.parametrize("request_type", [ - service.GetImportJobRequest, - dict, -]) -def test_get_import_job_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/importJobs/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.ImportJob.pb(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_import_job(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) - assert response.name == 'name_value' - assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_import_job_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_get_import_job") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_get_import_job") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GetImportJobRequest.pb(service.GetImportJobRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.ImportJob.to_json(resources.ImportJob()) - req.return_value.content = return_value - - request = service.GetImportJobRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.ImportJob() - - client.get_import_job(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_key_ring_rest_bad_request(request_type=service.CreateKeyRingRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.create_key_ring(request) - - -@pytest.mark.parametrize("request_type", [ - service.CreateKeyRingRequest, - dict, -]) -def test_create_key_ring_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2'} - request_init["key_ring"] = {'name': 'name_value', 'create_time': {'seconds': 751, 'nanos': 543}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateKeyRingRequest.meta.fields["key_ring"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["key_ring"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["key_ring"][field])): - del request_init["key_ring"][field][i][subfield] - else: - del request_init["key_ring"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.KeyRing( - name='name_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.KeyRing.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_key_ring(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.KeyRing) - assert response.name == 'name_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_key_ring_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_create_key_ring") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_create_key_ring") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateKeyRingRequest.pb(service.CreateKeyRingRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.KeyRing.to_json(resources.KeyRing()) - req.return_value.content = return_value - - request = service.CreateKeyRingRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.KeyRing() - - client.create_key_ring(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_crypto_key_rest_bad_request(request_type=service.CreateCryptoKeyRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.create_crypto_key(request) - - -@pytest.mark.parametrize("request_type", [ - service.CreateCryptoKeyRequest, - dict, -]) -def test_create_crypto_key_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - request_init["crypto_key"] = {'name': 'name_value', 'primary': {'name': 'name_value', 'state': 5, 'protection_level': 1, 'algorithm': 1, 'attestation': {'format_': 3, 'content': b'content_blob', 'cert_chains': {'cavium_certs': ['cavium_certs_value1', 'cavium_certs_value2'], 'google_card_certs': ['google_card_certs_value1', 'google_card_certs_value2'], 'google_partition_certs': ['google_partition_certs_value1', 'google_partition_certs_value2']}}, 'create_time': {'seconds': 751, 'nanos': 543}, 'generate_time': {}, 'destroy_time': {}, 'destroy_event_time': {}, 'import_job': 'import_job_value', 'import_time': {}, 'import_failure_reason': 'import_failure_reason_value', 'generation_failure_reason': 'generation_failure_reason_value', 'external_destruction_failure_reason': 'external_destruction_failure_reason_value', 'external_protection_level_options': {'external_key_uri': 'external_key_uri_value', 'ekm_connection_key_path': 'ekm_connection_key_path_value'}, 'reimport_eligible': True}, 'purpose': 1, 'create_time': {}, 'next_rotation_time': {}, 'rotation_period': {'seconds': 751, 'nanos': 543}, 'version_template': {'protection_level': 1, 'algorithm': 1}, 'labels': {}, 'import_only': True, 'destroy_scheduled_duration': {}, 'crypto_key_backend': 'crypto_key_backend_value', 'key_access_justifications_policy': {'allowed_access_reasons': [1]}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateCryptoKeyRequest.meta.fields["crypto_key"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["crypto_key"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["crypto_key"][field])): - del request_init["crypto_key"][field][i][subfield] - else: - del request_init["crypto_key"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_crypto_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_crypto_key_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_create_crypto_key") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_create_crypto_key") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateCryptoKeyRequest.pb(service.CreateCryptoKeyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.CryptoKey.to_json(resources.CryptoKey()) - req.return_value.content = return_value - - request = service.CreateCryptoKeyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CryptoKey() - - client.create_crypto_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_crypto_key_version_rest_bad_request(request_type=service.CreateCryptoKeyVersionRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.create_crypto_key_version(request) - - -@pytest.mark.parametrize("request_type", [ - service.CreateCryptoKeyVersionRequest, - dict, -]) -def test_create_crypto_key_version_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request_init["crypto_key_version"] = {'name': 'name_value', 'state': 5, 'protection_level': 1, 'algorithm': 1, 'attestation': {'format_': 3, 'content': b'content_blob', 'cert_chains': {'cavium_certs': ['cavium_certs_value1', 'cavium_certs_value2'], 'google_card_certs': ['google_card_certs_value1', 'google_card_certs_value2'], 'google_partition_certs': ['google_partition_certs_value1', 'google_partition_certs_value2']}}, 'create_time': {'seconds': 751, 'nanos': 543}, 'generate_time': {}, 'destroy_time': {}, 'destroy_event_time': {}, 'import_job': 'import_job_value', 'import_time': {}, 'import_failure_reason': 'import_failure_reason_value', 'generation_failure_reason': 'generation_failure_reason_value', 'external_destruction_failure_reason': 'external_destruction_failure_reason_value', 'external_protection_level_options': {'external_key_uri': 'external_key_uri_value', 'ekm_connection_key_path': 'ekm_connection_key_path_value'}, 'reimport_eligible': True} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateCryptoKeyVersionRequest.meta.fields["crypto_key_version"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["crypto_key_version"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["crypto_key_version"][field])): - del request_init["crypto_key_version"][field][i][subfield] - else: - del request_init["crypto_key_version"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_crypto_key_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_crypto_key_version_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_create_crypto_key_version") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_create_crypto_key_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateCryptoKeyVersionRequest.pb(service.CreateCryptoKeyVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) - req.return_value.content = return_value - - request = service.CreateCryptoKeyVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CryptoKeyVersion() - - client.create_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_import_crypto_key_version_rest_bad_request(request_type=service.ImportCryptoKeyVersionRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.import_crypto_key_version(request) - - -@pytest.mark.parametrize("request_type", [ - service.ImportCryptoKeyVersionRequest, - dict, -]) -def test_import_crypto_key_version_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(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.import_crypto_key_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_crypto_key_version_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_import_crypto_key_version") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_import_crypto_key_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.ImportCryptoKeyVersionRequest.pb(service.ImportCryptoKeyVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) - req.return_value.content = return_value - - request = service.ImportCryptoKeyVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CryptoKeyVersion() - - client.import_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_import_job_rest_bad_request(request_type=service.CreateImportJobRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.create_import_job(request) - - -@pytest.mark.parametrize("request_type", [ - service.CreateImportJobRequest, - dict, -]) -def test_create_import_job_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'parent': 'projects/sample1/locations/sample2/keyRings/sample3'} - request_init["import_job"] = {'name': 'name_value', 'import_method': 1, 'protection_level': 1, 'create_time': {'seconds': 751, 'nanos': 543}, 'generate_time': {}, 'expire_time': {}, 'expire_event_time': {}, 'state': 1, 'public_key': {'pem': 'pem_value'}, 'attestation': {'format_': 3, 'content': b'content_blob', 'cert_chains': {'cavium_certs': ['cavium_certs_value1', 'cavium_certs_value2'], 'google_card_certs': ['google_card_certs_value1', 'google_card_certs_value2'], 'google_partition_certs': ['google_partition_certs_value1', 'google_partition_certs_value2']}}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.CreateImportJobRequest.meta.fields["import_job"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["import_job"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["import_job"][field])): - del request_init["import_job"][field][i][subfield] - else: - del request_init["import_job"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.ImportJob( - name='name_value', - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, - protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.ImportJob.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.create_import_job(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) - assert response.name == 'name_value' - assert response.import_method == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_import_job_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_create_import_job") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_create_import_job") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.CreateImportJobRequest.pb(service.CreateImportJobRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.ImportJob.to_json(resources.ImportJob()) - req.return_value.content = return_value - - request = service.CreateImportJobRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.ImportJob() - - client.create_import_job(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_crypto_key_rest_bad_request(request_type=service.UpdateCryptoKeyRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'crypto_key': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_crypto_key(request) - - -@pytest.mark.parametrize("request_type", [ - service.UpdateCryptoKeyRequest, - dict, -]) -def test_update_crypto_key_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'crypto_key': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'}} - request_init["crypto_key"] = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4', 'primary': {'name': 'name_value', 'state': 5, 'protection_level': 1, 'algorithm': 1, 'attestation': {'format_': 3, 'content': b'content_blob', 'cert_chains': {'cavium_certs': ['cavium_certs_value1', 'cavium_certs_value2'], 'google_card_certs': ['google_card_certs_value1', 'google_card_certs_value2'], 'google_partition_certs': ['google_partition_certs_value1', 'google_partition_certs_value2']}}, 'create_time': {'seconds': 751, 'nanos': 543}, 'generate_time': {}, 'destroy_time': {}, 'destroy_event_time': {}, 'import_job': 'import_job_value', 'import_time': {}, 'import_failure_reason': 'import_failure_reason_value', 'generation_failure_reason': 'generation_failure_reason_value', 'external_destruction_failure_reason': 'external_destruction_failure_reason_value', 'external_protection_level_options': {'external_key_uri': 'external_key_uri_value', 'ekm_connection_key_path': 'ekm_connection_key_path_value'}, 'reimport_eligible': True}, 'purpose': 1, 'create_time': {}, 'next_rotation_time': {}, 'rotation_period': {'seconds': 751, 'nanos': 543}, 'version_template': {'protection_level': 1, 'algorithm': 1}, 'labels': {}, 'import_only': True, 'destroy_scheduled_duration': {}, 'crypto_key_backend': 'crypto_key_backend_value', 'key_access_justifications_policy': {'allowed_access_reasons': [1]}} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateCryptoKeyRequest.meta.fields["crypto_key"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["crypto_key"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["crypto_key"][field])): - del request_init["crypto_key"][field][i][subfield] - else: - del request_init["crypto_key"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_crypto_key(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_crypto_key_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_update_crypto_key") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_update_crypto_key") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateCryptoKeyRequest.pb(service.UpdateCryptoKeyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.CryptoKey.to_json(resources.CryptoKey()) - req.return_value.content = return_value - - request = service.UpdateCryptoKeyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CryptoKey() - - client.update_crypto_key(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_crypto_key_version_rest_bad_request(request_type=service.UpdateCryptoKeyVersionRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'crypto_key_version': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'}} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_crypto_key_version(request) - - -@pytest.mark.parametrize("request_type", [ - service.UpdateCryptoKeyVersionRequest, - dict, -]) -def test_update_crypto_key_version_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'crypto_key_version': {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'}} - request_init["crypto_key_version"] = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5', 'state': 5, 'protection_level': 1, 'algorithm': 1, 'attestation': {'format_': 3, 'content': b'content_blob', 'cert_chains': {'cavium_certs': ['cavium_certs_value1', 'cavium_certs_value2'], 'google_card_certs': ['google_card_certs_value1', 'google_card_certs_value2'], 'google_partition_certs': ['google_partition_certs_value1', 'google_partition_certs_value2']}}, 'create_time': {'seconds': 751, 'nanos': 543}, 'generate_time': {}, 'destroy_time': {}, 'destroy_event_time': {}, 'import_job': 'import_job_value', 'import_time': {}, 'import_failure_reason': 'import_failure_reason_value', 'generation_failure_reason': 'generation_failure_reason_value', 'external_destruction_failure_reason': 'external_destruction_failure_reason_value', 'external_protection_level_options': {'external_key_uri': 'external_key_uri_value', 'ekm_connection_key_path': 'ekm_connection_key_path_value'}, 'reimport_eligible': True} - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = service.UpdateCryptoKeyVersionRequest.meta.fields["crypto_key_version"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["crypto_key_version"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - {"field": field, "subfield": subfield, "is_repeated": is_repeated} - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["crypto_key_version"][field])): - del request_init["crypto_key_version"][field][i][subfield] - else: - del request_init["crypto_key_version"][field][subfield] - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_crypto_key_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_crypto_key_version_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_update_crypto_key_version") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_update_crypto_key_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateCryptoKeyVersionRequest.pb(service.UpdateCryptoKeyVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) - req.return_value.content = return_value - - request = service.UpdateCryptoKeyVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CryptoKeyVersion() - - client.update_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_update_crypto_key_primary_version_rest_bad_request(request_type=service.UpdateCryptoKeyPrimaryVersionRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.update_crypto_key_primary_version(request) - - -@pytest.mark.parametrize("request_type", [ - service.UpdateCryptoKeyPrimaryVersionRequest, - dict, -]) -def test_update_crypto_key_primary_version_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey( - name='name_value', - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend='crypto_key_backend_value', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.update_crypto_key_primary_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == 'name_value' - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == 'crypto_key_backend_value' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_crypto_key_primary_version_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_update_crypto_key_primary_version") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_update_crypto_key_primary_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.UpdateCryptoKeyPrimaryVersionRequest.pb(service.UpdateCryptoKeyPrimaryVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.CryptoKey.to_json(resources.CryptoKey()) - req.return_value.content = return_value - - request = service.UpdateCryptoKeyPrimaryVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CryptoKey() - - client.update_crypto_key_primary_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_destroy_crypto_key_version_rest_bad_request(request_type=service.DestroyCryptoKeyVersionRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.destroy_crypto_key_version(request) - - -@pytest.mark.parametrize("request_type", [ - service.DestroyCryptoKeyVersionRequest, - dict, -]) -def test_destroy_crypto_key_version_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(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.destroy_crypto_key_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_destroy_crypto_key_version_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_destroy_crypto_key_version") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_destroy_crypto_key_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.DestroyCryptoKeyVersionRequest.pb(service.DestroyCryptoKeyVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) - req.return_value.content = return_value - - request = service.DestroyCryptoKeyVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CryptoKeyVersion() - - client.destroy_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_restore_crypto_key_version_rest_bad_request(request_type=service.RestoreCryptoKeyVersionRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.restore_crypto_key_version(request) - - -@pytest.mark.parametrize("request_type", [ - service.RestoreCryptoKeyVersionRequest, - dict, -]) -def test_restore_crypto_key_version_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion( - name='name_value', - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job='import_job_value', - import_failure_reason='import_failure_reason_value', - generation_failure_reason='generation_failure_reason_value', - external_destruction_failure_reason='external_destruction_failure_reason_value', - reimport_eligible=True, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(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.restore_crypto_key_version(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == 'name_value' - assert response.state == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.algorithm == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - assert response.import_job == 'import_job_value' - assert response.import_failure_reason == 'import_failure_reason_value' - assert response.generation_failure_reason == 'generation_failure_reason_value' - assert response.external_destruction_failure_reason == 'external_destruction_failure_reason_value' - assert response.reimport_eligible is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restore_crypto_key_version_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_restore_crypto_key_version") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_restore_crypto_key_version") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.RestoreCryptoKeyVersionRequest.pb(service.RestoreCryptoKeyVersionRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) - req.return_value.content = return_value - - request = service.RestoreCryptoKeyVersionRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = resources.CryptoKeyVersion() - - client.restore_crypto_key_version(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_encrypt_rest_bad_request(request_type=service.EncryptRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.encrypt(request) - - -@pytest.mark.parametrize("request_type", [ - service.EncryptRequest, - dict, -]) -def test_encrypt_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.EncryptResponse( - name='name_value', - ciphertext=b'ciphertext_blob', - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.EncryptResponse.pb(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.encrypt(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.EncryptResponse) - assert response.name == 'name_value' - assert response.ciphertext == b'ciphertext_blob' - assert response.verified_plaintext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_encrypt_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_encrypt") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_encrypt") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.EncryptRequest.pb(service.EncryptRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.EncryptResponse.to_json(service.EncryptResponse()) - req.return_value.content = return_value - - request = service.EncryptRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.EncryptResponse() - - client.encrypt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_decrypt_rest_bad_request(request_type=service.DecryptRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.decrypt(request) - - -@pytest.mark.parametrize("request_type", [ - service.DecryptRequest, - dict, -]) -def test_decrypt_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.DecryptResponse( - plaintext=b'plaintext_blob', - used_primary=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.DecryptResponse.pb(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.decrypt(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.DecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.used_primary is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_decrypt_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_decrypt") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_decrypt") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.DecryptRequest.pb(service.DecryptRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.DecryptResponse.to_json(service.DecryptResponse()) - req.return_value.content = return_value - - request = service.DecryptRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.DecryptResponse() - - client.decrypt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_raw_encrypt_rest_bad_request(request_type=service.RawEncryptRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.raw_encrypt(request) - - -@pytest.mark.parametrize("request_type", [ - service.RawEncryptRequest, - dict, -]) -def test_raw_encrypt_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.RawEncryptResponse( - ciphertext=b'ciphertext_blob', - initialization_vector=b'initialization_vector_blob', - tag_length=1053, - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, - name='name_value', - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.RawEncryptResponse.pb(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.raw_encrypt(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.RawEncryptResponse) - assert response.ciphertext == b'ciphertext_blob' - assert response.initialization_vector == b'initialization_vector_blob' - assert response.tag_length == 1053 - assert response.verified_plaintext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.verified_initialization_vector_crc32c is True - assert response.name == 'name_value' - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_raw_encrypt_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_raw_encrypt") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_raw_encrypt") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.RawEncryptRequest.pb(service.RawEncryptRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.RawEncryptResponse.to_json(service.RawEncryptResponse()) - req.return_value.content = return_value - - request = service.RawEncryptRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.RawEncryptResponse() - - client.raw_encrypt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_raw_decrypt_rest_bad_request(request_type=service.RawDecryptRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.raw_decrypt(request) - - -@pytest.mark.parametrize("request_type", [ - service.RawDecryptRequest, - dict, -]) -def test_raw_decrypt_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.RawDecryptResponse( - plaintext=b'plaintext_blob', - protection_level=resources.ProtectionLevel.SOFTWARE, - verified_ciphertext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.RawDecryptResponse.pb(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.raw_decrypt(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.RawDecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.verified_ciphertext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.verified_initialization_vector_crc32c is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_raw_decrypt_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_raw_decrypt") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_raw_decrypt") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.RawDecryptRequest.pb(service.RawDecryptRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.RawDecryptResponse.to_json(service.RawDecryptResponse()) - req.return_value.content = return_value - - request = service.RawDecryptRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.RawDecryptResponse() - - client.raw_decrypt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_asymmetric_sign_rest_bad_request(request_type=service.AsymmetricSignRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.asymmetric_sign(request) - - -@pytest.mark.parametrize("request_type", [ - service.AsymmetricSignRequest, - dict, -]) -def test_asymmetric_sign_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.AsymmetricSignResponse( - signature=b'signature_blob', - verified_digest_crc32c=True, - name='name_value', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.AsymmetricSignResponse.pb(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.asymmetric_sign(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricSignResponse) - assert response.signature == b'signature_blob' - assert response.verified_digest_crc32c is True - assert response.name == 'name_value' - assert response.verified_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_asymmetric_sign_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_asymmetric_sign") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_asymmetric_sign") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.AsymmetricSignRequest.pb(service.AsymmetricSignRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.AsymmetricSignResponse.to_json(service.AsymmetricSignResponse()) - req.return_value.content = return_value - - request = service.AsymmetricSignRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.AsymmetricSignResponse() - - client.asymmetric_sign(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_asymmetric_decrypt_rest_bad_request(request_type=service.AsymmetricDecryptRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.asymmetric_decrypt(request) - - -@pytest.mark.parametrize("request_type", [ - service.AsymmetricDecryptRequest, - dict, -]) -def test_asymmetric_decrypt_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.AsymmetricDecryptResponse( - plaintext=b'plaintext_blob', - verified_ciphertext_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.AsymmetricDecryptResponse.pb(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.asymmetric_decrypt(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricDecryptResponse) - assert response.plaintext == b'plaintext_blob' - assert response.verified_ciphertext_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_asymmetric_decrypt_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_asymmetric_decrypt") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_asymmetric_decrypt") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.AsymmetricDecryptRequest.pb(service.AsymmetricDecryptRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.AsymmetricDecryptResponse.to_json(service.AsymmetricDecryptResponse()) - req.return_value.content = return_value - - request = service.AsymmetricDecryptRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.AsymmetricDecryptResponse() - - client.asymmetric_decrypt(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_mac_sign_rest_bad_request(request_type=service.MacSignRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.mac_sign(request) - - -@pytest.mark.parametrize("request_type", [ - service.MacSignRequest, - dict, -]) -def test_mac_sign_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.MacSignResponse( - name='name_value', - mac=b'mac_blob', - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.MacSignResponse.pb(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.mac_sign(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.MacSignResponse) - assert response.name == 'name_value' - assert response.mac == b'mac_blob' - assert response.verified_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_mac_sign_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_mac_sign") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_mac_sign") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.MacSignRequest.pb(service.MacSignRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.MacSignResponse.to_json(service.MacSignResponse()) - req.return_value.content = return_value - - request = service.MacSignRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.MacSignResponse() - - client.mac_sign(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_mac_verify_rest_bad_request(request_type=service.MacVerifyRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.mac_verify(request) - - -@pytest.mark.parametrize("request_type", [ - service.MacVerifyRequest, - dict, -]) -def test_mac_verify_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'name': 'projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.MacVerifyResponse( - name='name_value', - success=True, - verified_data_crc32c=True, - verified_mac_crc32c=True, - verified_success_integrity=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.MacVerifyResponse.pb(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.mac_verify(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.MacVerifyResponse) - assert response.name == 'name_value' - assert response.success is True - assert response.verified_data_crc32c is True - assert response.verified_mac_crc32c is True - assert response.verified_success_integrity is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_mac_verify_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_mac_verify") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_mac_verify") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.MacVerifyRequest.pb(service.MacVerifyRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.MacVerifyResponse.to_json(service.MacVerifyResponse()) - req.return_value.content = return_value - - request = service.MacVerifyRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.MacVerifyResponse() - - client.mac_verify(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_generate_random_bytes_rest_bad_request(request_type=service.GenerateRandomBytesRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {'location': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = mock.Mock() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = mock.Mock() - req.return_value = response_value - client.generate_random_bytes(request) - - -@pytest.mark.parametrize("request_type", [ - service.GenerateRandomBytesRequest, - dict, -]) -def test_generate_random_bytes_rest_call_success(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {'location': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), 'request') as req: - # Designate an appropriate value for the returned response. - return_value = service.GenerateRandomBytesResponse( - data=b'data_blob', - ) - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = service.GenerateRandomBytesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - req.return_value = response_value - response = client.generate_random_bytes(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateRandomBytesResponse) - assert response.data == b'data_blob' - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_generate_random_bytes_rest_interceptors(null_interceptor): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.KeyManagementServiceRestInterceptor(), - ) - client = KeyManagementServiceClient(transport=transport) - - with mock.patch.object(type(client.transport._session), "request") as req, \ - mock.patch.object(path_template, "transcode") as transcode, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "post_generate_random_bytes") as post, \ - mock.patch.object(transports.KeyManagementServiceRestInterceptor, "pre_generate_random_bytes") as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = service.GenerateRandomBytesRequest.pb(service.GenerateRandomBytesRequest()) - transcode.return_value = { - "method": "post", - "uri": "my_uri", - "body": pb_message, - "query_params": pb_message, - } - - req.return_value = mock.Mock() - req.return_value.status_code = 200 - return_value = service.GenerateRandomBytesResponse.to_json(service.GenerateRandomBytesResponse()) - req.return_value.content = return_value - - request = service.GenerateRandomBytesRequest() - metadata =[ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = service.GenerateRandomBytesResponse() - - client.generate_random_bytes(request, metadata=[("key", "val"), ("cephalopod", "squid"),]) - - pre.assert_called_once() - post.assert_called_once() - - -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_location(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.GetLocationRequest, - dict, -]) -def test_get_location_rest(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_location(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - - -def test_list_locations_rest_bad_request(request_type=locations_pb2.ListLocationsRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.list_locations(request) - - -@pytest.mark.parametrize("request_type", [ - locations_pb2.ListLocationsRequest, - dict, -]) -def test_list_locations_rest(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.list_locations(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - - -def test_get_iam_policy_rest_bad_request(request_type=iam_policy_pb2.GetIamPolicyRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.GetIamPolicyRequest, - dict, -]) -def test_get_iam_policy_rest(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_set_iam_policy_rest_bad_request(request_type=iam_policy_pb2.SetIamPolicyRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.set_iam_policy(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.SetIamPolicyRequest, - dict, -]) -def test_set_iam_policy_rest(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.set_iam_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - -def test_test_iam_permissions_rest_bad_request(request_type=iam_policy_pb2.TestIamPermissionsRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'resource': 'projects/sample1/locations/sample2/keyRings/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.test_iam_permissions(request) - - -@pytest.mark.parametrize("request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, - dict, -]) -def test_test_iam_permissions_rest(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'resource': 'projects/sample1/locations/sample2/keyRings/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.test_iam_permissions(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - -def test_get_operation_rest_bad_request(request_type=operations_pb2.GetOperationRequest): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type() - request = json_format.ParseDict({'name': 'projects/sample1/locations/sample2/operations/sample3'}, request) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, 'request') as req, pytest.raises(core_exceptions.BadRequest): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = '' - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_operation(request) - - -@pytest.mark.parametrize("request_type", [ - operations_pb2.GetOperationRequest, - dict, -]) -def test_get_operation_rest(request_type): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - request_init = {'name': 'projects/sample1/locations/sample2/operations/sample3'} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, 'request') as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode('UTF-8') - - req.return_value = response_value - - response = client.get_operation(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_initialize_client_w_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - assert client is not None - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_key_rings_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_key_rings), - '__call__') as call: - client.list_key_rings(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListKeyRingsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_crypto_keys_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_keys), - '__call__') as call: - client.list_crypto_keys(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListCryptoKeysRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_crypto_key_versions_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_crypto_key_versions), - '__call__') as call: - client.list_crypto_key_versions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListCryptoKeyVersionsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_list_import_jobs_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_import_jobs), - '__call__') as call: - client.list_import_jobs(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ListImportJobsRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_key_ring_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_key_ring), - '__call__') as call: - client.get_key_ring(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetKeyRingRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_crypto_key_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key), - '__call__') as call: - client.get_crypto_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetCryptoKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_crypto_key_version_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_crypto_key_version), - '__call__') as call: - client.get_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_public_key_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_public_key), - '__call__') as call: - client.get_public_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetPublicKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_get_import_job_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_import_job), - '__call__') as call: - client.get_import_job(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GetImportJobRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_key_ring_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_key_ring), - '__call__') as call: - client.create_key_ring(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateKeyRingRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_crypto_key_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key), - '__call__') as call: - client.create_crypto_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateCryptoKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_crypto_key_version_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_crypto_key_version), - '__call__') as call: - client.create_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_import_crypto_key_version_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.import_crypto_key_version), - '__call__') as call: - client.import_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.ImportCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_create_import_job_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), - '__call__') as call: - client.create_import_job(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.CreateImportJobRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_crypto_key_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), - '__call__') as call: - client.update_crypto_key(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_crypto_key_version_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_version), - '__call__') as call: - client.update_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_update_crypto_key_primary_version_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), - '__call__') as call: - client.update_crypto_key_primary_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyPrimaryVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_destroy_crypto_key_version_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.destroy_crypto_key_version), - '__call__') as call: - client.destroy_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DestroyCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_restore_crypto_key_version_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.restore_crypto_key_version), - '__call__') as call: - client.restore_crypto_key_version(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.RestoreCryptoKeyVersionRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_encrypt_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.encrypt), - '__call__') as call: - client.encrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.EncryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_decrypt_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.decrypt), - '__call__') as call: - client.decrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.DecryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_raw_encrypt_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.raw_encrypt), - '__call__') as call: - client.raw_encrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.RawEncryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_raw_decrypt_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.raw_decrypt), - '__call__') as call: - client.raw_decrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.RawDecryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_asymmetric_sign_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_sign), - '__call__') as call: - client.asymmetric_sign(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.AsymmetricSignRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_asymmetric_decrypt_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), - '__call__') as call: - client.asymmetric_decrypt(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.AsymmetricDecryptRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_mac_sign_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.mac_sign), - '__call__') as call: - client.mac_sign(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.MacSignRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_mac_verify_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.mac_verify), - '__call__') as call: - client.mac_verify(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.MacVerifyRequest() - - assert args[0] == request_msg - - -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -def test_generate_random_bytes_empty_call_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), - '__call__') as call: - client.generate_random_bytes(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = service.GenerateRandomBytesRequest() - - assert args[0] == request_msg - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - assert isinstance( - client.transport, - transports.KeyManagementServiceGrpcTransport, - ) - -def test_key_management_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.KeyManagementServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json" - ) - - -def test_key_management_service_base_transport(): - # Instantiate the base transport. - with mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport.__init__') as Transport: - Transport.return_value = None - transport = transports.KeyManagementServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - 'list_key_rings', - 'list_crypto_keys', - 'list_crypto_key_versions', - 'list_import_jobs', - 'get_key_ring', - 'get_crypto_key', - 'get_crypto_key_version', - 'get_public_key', - 'get_import_job', - 'create_key_ring', - 'create_crypto_key', - 'create_crypto_key_version', - 'import_crypto_key_version', - 'create_import_job', - 'update_crypto_key', - 'update_crypto_key_version', - 'update_crypto_key_primary_version', - 'destroy_crypto_key_version', - 'restore_crypto_key_version', - 'encrypt', - 'decrypt', - 'raw_encrypt', - 'raw_decrypt', - 'asymmetric_sign', - 'asymmetric_decrypt', - 'mac_sign', - 'mac_verify', - 'generate_random_bytes', - 'set_iam_policy', - 'get_iam_policy', - 'test_iam_permissions', - 'get_location', - 'list_locations', - 'get_operation', - ) - 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_key_management_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object(google.auth, 'load_credentials_from_file', autospec=True) as load_creds, mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KeyManagementServiceTransport( - 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', - 'https://www.googleapis.com/auth/cloudkms', -), - quota_project_id="octopus", - ) - - -def test_key_management_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, 'default', autospec=True) as adc, mock.patch('google.cloud.kms_v1.services.key_management_service.transports.KeyManagementServiceTransport._prep_wrapped_messages') as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.KeyManagementServiceTransport() - adc.assert_called_once() - - -def test_key_management_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - KeyManagementServiceClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - quota_project_id=None, - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceGrpcAsyncIOTransport, - ], -) -def test_key_management_service_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=( 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloudkms',), - quota_project_id="octopus", - ) - - -@pytest.mark.parametrize( - "transport_class", - [ - transports.KeyManagementServiceGrpcTransport, - transports.KeyManagementServiceGrpcAsyncIOTransport, - transports.KeyManagementServiceRestTransport, - ], -) -def test_key_management_service_transport_auth_gdch_credentials(transport_class): - host = 'https://language.com' - api_audience_tests = [None, 'https://language2.com'] - api_audience_expect = [host, 'https://language2.com'] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, 'default', autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock(return_value=gdch_mock) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with( - e - ) - - -@pytest.mark.parametrize( - "transport_class,grpc_helpers", - [ - (transports.KeyManagementServiceGrpcTransport, grpc_helpers), - (transports.KeyManagementServiceGrpcAsyncIOTransport, grpc_helpers_async) - ], -) -def test_key_management_service_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class( - quota_project_id="octopus", - scopes=["1", "2"] - ) - - create_channel.assert_called_with( - "cloudkms.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=( - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloudkms', -), - scopes=["1", "2"], - default_host="cloudkms.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - -@pytest.mark.parametrize("transport_class", [transports.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) -def test_key_management_service_grpc_transport_client_cert_source_for_mtls( - transport_class -): - cred = ga_credentials.AnonymousCredentials() - - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, - private_key=expected_key - ) - -def test_key_management_service_http_transport_client_cert_source_for_mtls(): - cred = ga_credentials.AnonymousCredentials() - with mock.patch("google.auth.transport.requests.AuthorizedSession.configure_mtls_channel") as mock_configure_mtls_channel: - transports.KeyManagementServiceRestTransport ( - 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_key_management_service_host_no_port(transport_name): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudkms.googleapis.com:443' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudkms.googleapis.com' - ) - -@pytest.mark.parametrize("transport_name", [ - "grpc", - "grpc_asyncio", - "rest", -]) -def test_key_management_service_host_with_port(transport_name): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions(api_endpoint='cloudkms.googleapis.com:8000'), - transport=transport_name, - ) - assert client.transport._host == ( - 'cloudkms.googleapis.com:8000' - if transport_name in ['grpc', 'grpc_asyncio'] - else 'https://cloudkms.googleapis.com:8000' - ) - -@pytest.mark.parametrize("transport_name", [ - "rest", -]) -def test_key_management_service_client_transport_session_collision(transport_name): - creds1 = ga_credentials.AnonymousCredentials() - creds2 = ga_credentials.AnonymousCredentials() - client1 = KeyManagementServiceClient( - credentials=creds1, - transport=transport_name, - ) - client2 = KeyManagementServiceClient( - credentials=creds2, - transport=transport_name, - ) - session1 = client1.transport.list_key_rings._session - session2 = client2.transport.list_key_rings._session - assert session1 != session2 - session1 = client1.transport.list_crypto_keys._session - session2 = client2.transport.list_crypto_keys._session - assert session1 != session2 - session1 = client1.transport.list_crypto_key_versions._session - session2 = client2.transport.list_crypto_key_versions._session - assert session1 != session2 - session1 = client1.transport.list_import_jobs._session - session2 = client2.transport.list_import_jobs._session - assert session1 != session2 - session1 = client1.transport.get_key_ring._session - session2 = client2.transport.get_key_ring._session - assert session1 != session2 - session1 = client1.transport.get_crypto_key._session - session2 = client2.transport.get_crypto_key._session - assert session1 != session2 - session1 = client1.transport.get_crypto_key_version._session - session2 = client2.transport.get_crypto_key_version._session - assert session1 != session2 - session1 = client1.transport.get_public_key._session - session2 = client2.transport.get_public_key._session - assert session1 != session2 - session1 = client1.transport.get_import_job._session - session2 = client2.transport.get_import_job._session - assert session1 != session2 - session1 = client1.transport.create_key_ring._session - session2 = client2.transport.create_key_ring._session - assert session1 != session2 - session1 = client1.transport.create_crypto_key._session - session2 = client2.transport.create_crypto_key._session - assert session1 != session2 - session1 = client1.transport.create_crypto_key_version._session - session2 = client2.transport.create_crypto_key_version._session - assert session1 != session2 - session1 = client1.transport.import_crypto_key_version._session - session2 = client2.transport.import_crypto_key_version._session - assert session1 != session2 - session1 = client1.transport.create_import_job._session - session2 = client2.transport.create_import_job._session - assert session1 != session2 - session1 = client1.transport.update_crypto_key._session - session2 = client2.transport.update_crypto_key._session - assert session1 != session2 - session1 = client1.transport.update_crypto_key_version._session - session2 = client2.transport.update_crypto_key_version._session - assert session1 != session2 - session1 = client1.transport.update_crypto_key_primary_version._session - session2 = client2.transport.update_crypto_key_primary_version._session - assert session1 != session2 - session1 = client1.transport.destroy_crypto_key_version._session - session2 = client2.transport.destroy_crypto_key_version._session - assert session1 != session2 - session1 = client1.transport.restore_crypto_key_version._session - session2 = client2.transport.restore_crypto_key_version._session - assert session1 != session2 - session1 = client1.transport.encrypt._session - session2 = client2.transport.encrypt._session - assert session1 != session2 - session1 = client1.transport.decrypt._session - session2 = client2.transport.decrypt._session - assert session1 != session2 - session1 = client1.transport.raw_encrypt._session - session2 = client2.transport.raw_encrypt._session - assert session1 != session2 - session1 = client1.transport.raw_decrypt._session - session2 = client2.transport.raw_decrypt._session - assert session1 != session2 - session1 = client1.transport.asymmetric_sign._session - session2 = client2.transport.asymmetric_sign._session - assert session1 != session2 - session1 = client1.transport.asymmetric_decrypt._session - session2 = client2.transport.asymmetric_decrypt._session - assert session1 != session2 - session1 = client1.transport.mac_sign._session - session2 = client2.transport.mac_sign._session - assert session1 != session2 - session1 = client1.transport.mac_verify._session - session2 = client2.transport.mac_verify._session - assert session1 != session2 - session1 = client1.transport.generate_random_bytes._session - session2 = client2.transport.generate_random_bytes._session - assert session1 != session2 -def test_key_management_service_grpc_transport_channel(): - channel = grpc.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.KeyManagementServiceGrpcTransport( - 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_key_management_service_grpc_asyncio_transport_channel(): - channel = aio.secure_channel('http://localhost/', grpc.local_channel_credentials()) - - # Check that channel is used if provided. - transport = transports.KeyManagementServiceGrpcAsyncIOTransport( - 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.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) -def test_key_management_service_transport_channel_mtls_with_client_cert_source( - transport_class -): - with mock.patch("grpc.ssl_channel_credentials", autospec=True) as grpc_ssl_channel_cred: - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, 'default') as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize("transport_class", [transports.KeyManagementServiceGrpcTransport, transports.KeyManagementServiceGrpcAsyncIOTransport]) -def test_key_management_service_transport_channel_mtls_with_adc( - transport_class -): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object(transport_class, "create_channel") as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_crypto_key_path(): - project = "squid" - location = "clam" - key_ring = "whelk" - crypto_key = "octopus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, ) - actual = KeyManagementServiceClient.crypto_key_path(project, location, key_ring, crypto_key) - assert expected == actual - - -def test_parse_crypto_key_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "key_ring": "cuttlefish", - "crypto_key": "mussel", - } - path = KeyManagementServiceClient.crypto_key_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_crypto_key_path(path) - assert expected == actual - -def test_crypto_key_version_path(): - project = "winkle" - location = "nautilus" - key_ring = "scallop" - crypto_key = "abalone" - crypto_key_version = "squid" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) - actual = KeyManagementServiceClient.crypto_key_version_path(project, location, key_ring, crypto_key, crypto_key_version) - assert expected == actual - - -def test_parse_crypto_key_version_path(): - expected = { - "project": "clam", - "location": "whelk", - "key_ring": "octopus", - "crypto_key": "oyster", - "crypto_key_version": "nudibranch", - } - path = KeyManagementServiceClient.crypto_key_version_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_crypto_key_version_path(path) - assert expected == actual - -def test_import_job_path(): - project = "cuttlefish" - location = "mussel" - key_ring = "winkle" - import_job = "nautilus" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/importJobs/{import_job}".format(project=project, location=location, key_ring=key_ring, import_job=import_job, ) - actual = KeyManagementServiceClient.import_job_path(project, location, key_ring, import_job) - assert expected == actual - - -def test_parse_import_job_path(): - expected = { - "project": "scallop", - "location": "abalone", - "key_ring": "squid", - "import_job": "clam", - } - path = KeyManagementServiceClient.import_job_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_import_job_path(path) - assert expected == actual - -def test_key_ring_path(): - project = "whelk" - location = "octopus" - key_ring = "oyster" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}".format(project=project, location=location, key_ring=key_ring, ) - actual = KeyManagementServiceClient.key_ring_path(project, location, key_ring) - assert expected == actual - - -def test_parse_key_ring_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "key_ring": "mussel", - } - path = KeyManagementServiceClient.key_ring_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_key_ring_path(path) - assert expected == actual - -def test_public_key_path(): - project = "winkle" - location = "nautilus" - key_ring = "scallop" - crypto_key = "abalone" - crypto_key_version = "squid" - expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}/publicKey".format(project=project, location=location, key_ring=key_ring, crypto_key=crypto_key, crypto_key_version=crypto_key_version, ) - actual = KeyManagementServiceClient.public_key_path(project, location, key_ring, crypto_key, crypto_key_version) - assert expected == actual - - -def test_parse_public_key_path(): - expected = { - "project": "clam", - "location": "whelk", - "key_ring": "octopus", - "crypto_key": "oyster", - "crypto_key_version": "nudibranch", - } - path = KeyManagementServiceClient.public_key_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_public_key_path(path) - assert expected == actual - -def test_common_billing_account_path(): - billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format(billing_account=billing_account, ) - actual = KeyManagementServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "mussel", - } - path = KeyManagementServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_billing_account_path(path) - assert expected == actual - -def test_common_folder_path(): - folder = "winkle" - expected = "folders/{folder}".format(folder=folder, ) - actual = KeyManagementServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "nautilus", - } - path = KeyManagementServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_folder_path(path) - assert expected == actual - -def test_common_organization_path(): - organization = "scallop" - expected = "organizations/{organization}".format(organization=organization, ) - actual = KeyManagementServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "abalone", - } - path = KeyManagementServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.parse_common_organization_path(path) - assert expected == actual - -def test_common_project_path(): - project = "squid" - expected = "projects/{project}".format(project=project, ) - actual = KeyManagementServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "clam", - } - path = KeyManagementServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.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 = KeyManagementServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - } - path = KeyManagementServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = KeyManagementServiceClient.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.KeyManagementServiceTransport, '_prep_wrapped_messages') as prep: - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object(transports.KeyManagementServiceTransport, '_prep_wrapped_messages') as prep: - transport_class = KeyManagementServiceClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - -def test_get_operation(transport: str = "grpc"): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation() - response = client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) -@pytest.mark.asyncio -async def test_get_operation_async(transport: str = "grpc_asyncio"): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = operations_pb2.GetOperationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) - -def test_get_operation_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value 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 = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = operations_pb2.GetOperationRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - await client.get_operation(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_get_operation_from_dict(): - client = KeyManagementServiceClient( - 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 = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_operation), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation() - ) - response = await client.get_operation( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_list_locations(transport: str = "grpc"): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - response = client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) -@pytest.mark.asyncio -async def test_list_locations_async(transport: str = "grpc_asyncio"): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.ListLocationsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) - -def test_list_locations_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = locations_pb2.ListLocationsResponse() - - client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] -@pytest.mark.asyncio -async def test_list_locations_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.ListLocationsRequest() - request.name = "locations" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - await client.list_locations(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations",) in kw["metadata"] - -def test_list_locations_from_dict(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.ListLocationsResponse() - - response = client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_list_locations_from_dict_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.ListLocationsResponse() - ) - response = await client.list_locations( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_get_location(transport: str = "grpc"): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - response = client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) -@pytest.mark.asyncio -async def test_get_location_async(transport: str = "grpc_asyncio"): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = locations_pb2.GetLocationRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) - -def test_get_location_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials()) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = locations_pb2.Location() - - client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] -@pytest.mark.asyncio -async def test_get_location_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials() - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = locations_pb2.GetLocationRequest() - request.name = "locations/abc" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_location), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - await client.get_location(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=locations/abc",) in kw["metadata"] - -def test_get_location_from_dict(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = locations_pb2.Location() - - response = client.get_location( - request={ - "name": "locations/abc", - } - ) - call.assert_called() -@pytest.mark.asyncio -async def test_get_location_from_dict_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_locations), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - locations_pb2.Location() - ) - response = await client.get_location( - request={ - "name": "locations", - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - response = client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" -@pytest.mark.asyncio -async def test_set_iam_policy_async(transport: str = "grpc_asyncio"): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.SetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - response = await client.set_iam_policy(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - -def test_set_iam_policy_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] -@pytest.mark.asyncio -async def test_set_iam_policy_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.SetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.set_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - -def test_set_iam_policy_from_dict(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -@pytest.mark.asyncio -async def test_set_iam_policy_from_dict_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.set_iam_policy( - request={ - "resource": "resource_value", - "policy": policy_pb2.Policy(version=774), - } - ) - call.assert_called() - - -def test_get_iam_policy(transport: str = "grpc"): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) - - response = client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -@pytest.mark.asyncio -async def test_get_iam_policy_async(transport: str = "grpc_asyncio"): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.GetIamPolicyRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy(version=774, etag=b"etag_blob",) - ) - - response = await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - - assert response.version == 774 - - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy_pb2.Policy() - - client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_get_iam_policy_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.GetIamPolicyRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_iam_policy), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) - - await client.get_iam_policy(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = policy_pb2.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_get_iam_policy_from_dict_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy_pb2.Policy() - ) - - response = await client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = "grpc"): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], - ) - - response = client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_async(transport: str = "grpc_asyncio"): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy_pb2.TestIamPermissionsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse(permissions=["permissions_value"],) - ) - - response = await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_test_iam_permissions_field_headers_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = iam_policy_pb2.TestIamPermissionsRequest() - request.resource = "resource/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - await client.test_iam_permissions(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = iam_policy_pb2.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - -@pytest.mark.asyncio -async def test_test_iam_permissions_from_dict_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.test_iam_permissions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy_pb2.TestIamPermissionsResponse() - ) - - response = await client.test_iam_permissions( - request={ - "resource": "resource_value", - "permissions": ["permissions_value"], - } - ) - call.assert_called() - - -def test_transport_close_grpc(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -@pytest.mark.asyncio -async def test_transport_close_grpc_asyncio(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio" - ) - with mock.patch.object(type(getattr(client.transport, "_grpc_channel")), "close") as close: - async with client: - close.assert_not_called() - close.assert_called_once() - - -def test_transport_close_rest(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest" - ) - with mock.patch.object(type(getattr(client.transport, "_session")), "close") as close: - with client: - close.assert_not_called() - close.assert_called_once() - - -def test_client_ctx(): - transports = [ - 'rest', - 'grpc', - ] - for transport in transports: - client = KeyManagementServiceClient( - 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", [ - (KeyManagementServiceClient, transports.KeyManagementServiceGrpcTransport), - (KeyManagementServiceAsyncClient, transports.KeyManagementServiceGrpcAsyncIOTransport), -]) -def test_api_key_credentials(client_class, transport_class): - with mock.patch.object( - google.auth._default, "get_api_key_credentials", create=True - ) as get_api_key_credentials: - mock_cred = mock.Mock() - get_api_key_credentials.return_value = mock_cred - options = client_options.ClientOptions() - options.api_key = "api_key" - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class(client_options=options) - patched.assert_called_once_with( - credentials=mock_cred, - credentials_file=None, - host=client._DEFAULT_ENDPOINT_TEMPLATE.format(UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE), - scopes=None, - client_cert_source_for_mtls=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - always_use_jwt_access=True, - api_audience=None, - ) diff --git a/packages/google-cloud-kms/google/cloud/kms/gapic_version.py b/packages/google-cloud-kms/google/cloud/kms/gapic_version.py index d98a058ea331..558c8aab67c5 100644 --- a/packages/google-cloud-kms/google/cloud/kms/gapic_version.py +++ b/packages/google-cloud-kms/google/cloud/kms/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.1.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py index d98a058ea331..558c8aab67c5 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.1.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py index 1cf5fc19392b..b30a8ca4ed64 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py @@ -693,6 +693,8 @@ class CryptoKeyVersionAlgorithm(proto.Enum): The suffix following ``HMAC_`` corresponds to the hash algorithm being used (eg. SHA256). + Algorithms beginning with ``PQ_`` are post-quantum. + For more information, see [Key purposes and algorithms] (https://cloud.google.com/kms/docs/algorithms). diff --git a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json index 667513ed5d0f..a5e165bff4c4 100644 --- a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json +++ b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-kms", - "version": "3.1.1" + "version": "0.1.0" }, "snippets": [ {